简体   繁体   English

无法在 MERN 项目中将请求从客户端发送到服务器端

[英]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"}/> . username来自另一个我写的文件<Feed username={"Shibly"}/> I want to have data from localhost:3000/api/posts/profile/Shibly , but I'm getting 404 error.我想从localhost:3000/api/posts/profile/Shibly获取数据,但出现404错误。

Here is the screenshot of network tab.这是网络选项卡的屏幕截图。 截屏

Note that, await axios.get("posts/timeline/638b46766863c22bd1c7e242") is working properly.请注意, await axios.get("posts/timeline/638b46766863c22bd1c7e242")工作正常。

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.首先,您正在从我从您的网络选项卡中看到的前端访问这个 API 端点。 Please check whether this API endpoint is exist or not on the backend side.请检查此 API 端点在后端是否存在。

http://localhost:3000/profile/posts/profile/Shibly 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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