Node.js应用中通过指定post id路径创建评论功能失效怎么办?
问题原因
你遇到的是Express路由路径拼接冲突,以及评论模型缺少文章关联字段两个核心问题:
- 路由重复拼接:你在
index.js中已经将评论路由挂载到了/api/posts/:id前缀下,同时评论路由内部的POST接口又写了/posts/:id/comment路径,两者拼接后的完整路径为/api/posts/:id/posts/:id/comment,和你实际请求的/api/posts/6137668b697dd2448c3f454c/comment完全不匹配,所以返回404找不到对应POST接口。 - 评论未关联文章:当前你的Comment模型没有存储对应文章ID的字段,就算路由通了,也无法实现「指定文章下创建评论」的业务需求。
修复步骤
1. 调整评论路由路径
修改Comment路由文件的接口定义,去掉重复的路径前缀,同时新增关联文章ID的逻辑:
const router = require("express").Router() const Comment = require("../models/Comment") // 因为已挂载到/api/posts/:id前缀下,此处直接写/comment即可 router.post("/comment", async (req, res) =>{ // 把路由参数中的文章ID赋值给评论数据 const commentData = { ...req.body, postId: req.params.id } const newComment = new Comment(commentData); try{ const savedComment = await newComment.save(); res.status(200).json(savedComment) }catch(err){ res.status(500).json(err) } }) module.exports = router
2. 给Comment模型新增文章关联字段
修改Comment模型文件,新增postId字段存储关联的文章ID:
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const CommentSchema = new mongoose.Schema( { title:{ type: String, required: true, unique: true }, description:{ type: String, required: true, }, username:{ type: Schema.Types.ObjectId, ref: 'User' }, // 新增关联文章的ID字段 postId: { type: Schema.Types.ObjectId, ref: 'Post', // 对应你的文章模型名称 required: true } }, {timestamps: true} ); // 原有注释写错了,模块名是Comment不是Post,建议修正 module.exports = mongoose.model("Comment", CommentSchema);
3. 检查index.js的路由引入
确保你在index.js中正确引入了评论路由,示例如下:
const express = require("express"); const app = express(); const mongoose = require("mongoose"); // 新增这行,路径对应你实际的评论路由文件位置 const commentRoute = require("./routes/comment") // 原有挂载逻辑不需要改 app.use("/api/posts/:id", commentRoute) // 其他服务启动代码...
改完之后重启服务,再请求/api/posts/[文章ID]/comment路径就能正常创建关联对应文章的评论了。
内容的提问来源于stack exchange,提问作者kinhs
相关产品推荐
相关产品推荐

