MERN项目客户端请求服务端出现404错误求助
MERN项目/profile/:username路由404错误排查
问题概述
MERN项目中,请求localhost:3000/api/posts/profile/Shibly返回404错误,但posts/timeline/638b46766863c22bd1c7e242接口可正常工作,此前功能无异常。
相关代码
后端路由
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) // 错误:使用req而非res设置响应状态 } catch (err) { res.status(500).json(err); } })
前端请求
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由父组件传入:
<Feed username="Shibly"/>
异常细节
网络请求显示实际请求路径为http://localhost:3000/posts/profile/Shibly,缺少预期的/api前缀;同时后端代码存在请求对象调用status方法的错误,会导致服务器内部错误。
解决步骤
- 修复后端响应错误:将
req.status(200).json(posts)改为res.status(200).json(posts),res才是响应对象,具备status和json方法。 - 补全前端请求前缀:将前端请求路径改为
"/api/posts/profile/"+username,确保与后端路由挂载路径匹配(假设后端posts路由挂载在/api下)。 - 优化错误处理:后端添加用户不存在的判断,避免
user._id引发的报错:const user = await User.findOne({ username: req.params.username }); if (!user) { return res.status(404).json({ message: "用户不存在" }); } - 统一axios配置(可选):设置axios的
baseURL为"http://localhost:3000/api",后续请求可省略前缀,简化代码:axios.defaults.baseURL = "http://localhost:3000/api"; // 请求示例 await axios.get(`posts/profile/${username}`)
内容的提问来源于stack exchange,提问作者Samiul Islam Shibly
相关产品推荐
相关产品推荐

