简体   繁体   中英

Cannot send request from client side to server side in a MERN project

While working on a personal project, everything was fine. But unfortunately I'm having a peculiar problem, as I cannot find out the reason behind this problem. Please let me describe the problem. Here the the backend point to which I'm trying to send requests from frontend.

router.get("/profile/:username", async (req, res) => {
    try {
        const user = await User.findOne({ username: req.params.username })
        const posts = await Post.find({ userId: user._id })
        req.status(200).json(posts)
    } catch (err) {
        res.status(500).json(err);
    }
})

This is my frontend point from where I'm trying to send requests

useEffect(() => {
    const fetchPosts = async () => {
      const res = username
        ? await axios.get("posts/profile/"+username)
        : await axios.get("posts/timeline/638b46766863c22bd1c7e242")
      setPosts(res.data)
    }
    fetchPosts()
  }, [username])

username is coming from another file where I wrote <Feed username={"Shibly"}/> . I want to have data from localhost:3000/api/posts/profile/Shibly , but I'm getting 404 error.

Here is the screenshot of network tab. 截屏

Note that, await axios.get("posts/timeline/638b46766863c22bd1c7e242") is working properly.

Please someone help me. Thanks in advance.

First, you are hitting this API endpoint from the front end that I see from your network tab. Please check whether this API endpoint is exist or not on the backend side.

http://localhost:3000/profile/posts/profile/Shibly

Also, you can use this way for the dynamic route in frontend

useEffect(() => {
    const fetchPosts = async () => {
      const res = username
        ? await         axios.get(`posts/profile/:${username}`)
        : await axios.get("posts/timeline/638b46766863c22bd1c7e242")
      setPosts(res.data)
    }
    fetchPosts()
  }, [username])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM