【发布时间】: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