【问题标题】:why is create new comment not working in my node.js application?为什么在我的 node.js 应用程序中创建新评论不起作用?
【发布时间】:2021-09-08 00:25:18
【问题描述】:

我正在尝试在我的 node.js 应用程序中创建新评论,但它返回错误。我实际上是在尝试使用我的帖子路径在特定帖子下创建新评论。这是我的代码:

评论模型

  const mongoose = require("mongoose"); //import 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'
    },
   
  }, {timestamps: true}
   );
 //exporting this schema
 module.exports = mongoose.model("Comment", CommentSchema); //the module name is "Post"

评论路线

const router = require("express").Router()
const Comment = require("../models/Comment")

router.post("/posts/:id/comment", async (req, res) =>{
const newComment = new Comment(req.body);//we create a new category for the database
    
try{
    const savedComment = await newComment.save();
    res.status(200).json(savedComment)
}catch(err){
    res.status(500).json(err)
}
})

Index.js

const express = require("express");//creating the express server
const app = express(); //creating the application
const mongoose = require("mongoose");

app.use("/api/posts/:id", commentRoute)

如果我不针对“/posts/:id/comment 路径和目标评论根路径“/”,则评论创建在邮递员中工作。但我正在尝试使用 post :id 在帖子内创建评论.它不工作。它向邮递员抛出这个错误:

邮递员错误

<head>
<meta charset="utf-8">
<title>Error</title>
</head>

<body>
<pre>Cannot POST /api/posts/6137668b697dd2448c3f454c/comment</pre>
</body>

我附上了邮递员错误和设置的屏幕截图

【问题讨论】:

  • 谢谢,我已经更正了
  • 快速浏览后,我想知道是不是 /api/ 前缀给您带来了麻烦。路由器接受"/posts/:id/comment",但安装在"/api/posts/:id" 你能确认它是否应该是/api/posts/:id/comment?
  • 我确实添加了,但没有用。我的意思是“/api/posts/:id/comment”也不起作用。
  • 路由器安装在/api/posts/:id,所以解决方法实际上是调用router.post("/comment", ...来响应/api/posts/:id/comment

标签: node.js mongodb express mongoose


【解决方案1】:

您当前设置路线的方式,期望您的路径如下所示:

/api/posts/:id/posts/:id/comment

当你的 cmetsRou​​te 文件中的代码被执行时,路径已经在/api/posts/:id,所以你的评论路径只需要检查路径的最后一部分/comment。

重写你的commentRoute,让它看起来更像这样:

// ------------------------- /api/posts/:id ------------------

const router = require("express").Router()
const Comment = require("../models/Comment")

router.post("/comment", async (req, res) => {
     const newComment = new Comment(req.body);
    
     try{
         const savedComment = await newComment.save();
         res.status(200).json(savedComment);
     } catch(err) {
         res.status(500).json(err);
     }
});

注意:我个人喜欢将该注释放在我所有路由文件的顶部,以便在到达此文件中的代码时知道路径是什么样的。

【讨论】:

  • 感谢您的帮助。如果我遵循此路径,如何为单个帖子分配评论?因为cmets是在特定帖子下制作的。
  • 您必须使用.Router({ mergeParams: true }); 创建路由器,才能将路由挂载点的id 包含在您的req.params 中参见stackoverflow.com/a/32140649/1563833
【解决方案2】:

因为您将路由器安装在/api/posts/:id,所以您应该更改:

router.post("/posts/:id/comment", async (req, res) =>{

到:

router.post("/comment", async (req, res) =>{

然后改变:

const router = require("express").Router()

到:

const router = require("express").Router({ mergeParams: true })

那么您的id 可以在/comment 的处理程序中的req.params.id 获得。例如:

router.post("/comment", async (req, res) => {
  console.log(`Commenting on ${req.params.id)}`);
  // ...

【讨论】:

  • 非常感谢您帮助我。如果我的评论路由路径是这样的:router.post("/post/:id/comment", async (req, res) =>{}。如何在不使用 mergeParams 的情况下正确安装路由器?我的 api路径如下所示:app.use("/api/posts/:id/comment"?
  • 您可以将路由器安装在/api。例如:app.use("/api", commentRoute) 但要注意 post 和 posts 是不同的。 (也许这只是您评论中的一个错字)。
  • 我其实想说 router.post("/posts/:id/comment", async (req, res) =>{})。这意味着,我的意思是帖子。有了这个评论路由路径,我可以使用 app.use("/api", commentRoute) 而不使用 mergeParams ?.
  • @kinhs,没错。如果您有嵌套路由并且参数来自父级(如我的帖子中所示),您只需要使用mergeParams 在您的情况下,如果您只希望父挂载点是无参数的/api,那么嵌套的 comment 路由决定了:id 参数,因此id 参数将在没有mergeParams 的情况下可用。
  • 哪个最好,我还是比较瘦的。您的方法似乎有效,因为我可以在数据库中看到我的 cmets。但如果我获取同一篇文章,评论将是一个空数组。但是id会在那里。另外,如果我通过邮递员发表评论,它会返回空正文,但状态为 200。如果你检查数据库评论集合,你会看到同样的评论。我的创建评论逻辑有问题吗?
猜你喜欢
  • 2015-01-13
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
相关资源
最近更新 更多