Express+React项目调用/createPost接口返回404状态码问题求助
问题根因
路由路径不匹配:
你在服务端index.js中注册帖子路由时指定了前缀/new:
app.use("/new", require("./routes/postRoute"));
这意味着postRoute.js中定义的所有路由都会自动拼接/new前缀,你在postRoute.js里写的/createPost接口,完整的请求路径实际是http://localhost:3001/new/createPost,但你前端现在请求的是http://localhost:3001/createPost,缺少前缀导致404报错。
解决方案(二选一即可)
- 方案1:修改前端Axios请求地址,将请求路径调整为
/new/createPost - 方案2:修改服务端路由注册规则,移除
postRoute的前缀,将index.js中的注册代码改为:
app.use("/", require("./routes/postRoute"));
其他需要修复的潜在问题
- 你的帖子创建接口没有给前端返回响应,且
newPost.save()是异步操作,没有等待执行完成会导致前端请求超时,将postRoute.js的接口逻辑修改为:
router.route("/createPost").post(async (req, res) => { try { const title = req.body.title; const body = req.body.body; const newPost = new Post({ title, body }); await newPost.save(); res.status(200).json({ message: "创建成功", post: newPost }); } catch (err) { res.status(500).json({ message: "创建失败", error: err.message }); } })
- 前端Axios请求需要添加错误捕获逻辑,避免出现
Uncaught (in promise)类报错。
内容的提问来源于stack exchange,提问作者Gigi Carti
相关产品推荐
相关产品推荐

