I got an error: Request failed with status code 404 AxiosError: Request failed with status code 404

1k Views Asked by At

I'm new to React and trying to go through a tutorial react social using React, Express, MongoDB and Node with axios for getting data from the backend. I have a component Feed to get all the posts made by the user and the user he follows.

The Feed component works well in the home page(localhost:3000) showing the proper posts, but when I turn to the profile page(localhost:3000/post/username) which also uses Feed, I got the ERROR Request failed with status code 404 AxiosError: Request failed with status code 404.

And in the browser console it shows: Axois Error

It seems it made a GET request to port 3000 which is the react port, but server port is 8800. It's just weird.

Here is my Feed Component:

import { useEffect, useState } from 'react';
import Post from "../post/Post";
import Share from "../share/Share";
import "./feed.css";
import axios from "axios";
// axios.defaults.baseURL = 'http://localhost:8800/api/';

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

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("posts/timeline/64e31eb40a9c1595ef8f425b");
      setPosts(res.data);
    }
    fetchPosts();

  }, []);
  return (
    <div className="feed">
      <div className="feedWrapper">
        <Share />
        {posts.map((p) => (
          <Post key={p._id} post={p} />
        ))}
      </div>
    </div>
  )
}

and this is backend:

//get timeline a posts
router.get("/timeline/:userId", async (req, res) => {
  try {
    const currentUser = await User.findById(req.params.userId);
    const userPosts = await Post.find({ userId: currentUser._id });
    const friendPosts = await Promise.all(
      currentUser.followings.map((friendId) => {
        return Post.find({ userId: friendId });
      })
    );
     res.status(200).json(userPosts.concat(...friendPosts));
  } catch (err) {
    res.status(500).json(err);
  }
});

Any help is appreciated!!

I used "proxy": "http://localhost:8800/api" in package.json and also tried setting "axois.defaults.baseURL="http://localhost:8800/api"" and it didn't help.

And I've restarted the backend and frontend multiple times, not working, showing the same erros

1

There are 1 best solutions below

1
victorkurauchi On

From the image you provided, it looks like the axios request is going to your frontend application (trying to fetch a route which doesn't exist).

You could just try changing axios.get() directly with the API URL for the sake of your tests

const res = await axios.get("http://localhost:8800/api/posts/timeline/64e31eb40a9c1595ef8f425b");

Later on you can improve the code to provide the Axios client for you with the default config as part of the instance

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

And then in you Feed component you would just

instance.get('/posts/timeline')