Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I am learning to connect my React app to my nodejs backend by following a video tutorial from YouTube. I did everything so far based on the tutorial but I am getting error at this stage and I can't seem to figure it out. Google couldnt help me too. I am trying to fetch data from the data base on the homepage. Here is the error messages on Google chrome browser:

GET http://localhost:3000/posts 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)


This is the code from the React file named home.jsx:

import { useEffect, useState } from 'react';
import Header from '../../components/header/header';
import Posts from '../../components/posts/posts';
import Sidebar from '../../components/sidebar/sidebar';
import './home.css';
import axios from "axios";

export default function Home() {
const [posts, setPosts] = useState([]);

useEffect(() =>{
    const fetchPosts = async () =>{
        const res = await axios.get("/posts")
     console.log(res)
    }
    fetchPosts()
}, [])
return (
   <>
        <Header/>
        <div className='home'>
            <Posts/>
            <Sidebar/>
        </div>
    </>
 )
 }


This is the node.js route path:

const postRoute = require("./routes/posts");
app.use("/api/posts", postRoute);



This is the package.json api path:


]
   }, "proxy": "http://localhost:5000/api"
   }


What I have tried:

I have searched on google for solutions but couldn't find any thing that could help.
Posted
Updated 18-Oct-22 3:21am

I had the exact same error in my axios.post method, and this link helped

https://stackoverflow.com/questions/50687064/method-post-with-axios-giving-error-404-reactjs

I solved it by adding the whole url in the post method.

in your home.jsx file, instead of this,
const res = await axios.get("/posts")

use:
const res = await axios.get("http://localhost:3000/posts")
 
Share this answer
 
just restart your server by typing npm start in both client and api directory
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900