我正在開發一個 Crud 專案(帶有身份驗證、帖子和評論),我在理解如何有效地進行路由并將帖子與評論鏈接時遇到了一些麻煩。
這是我的評論路線:
router.post("/:id", auth, comCtrl.createComment);
router.post("/:id", auth, comCtrl.getPostComments);
router.post("/:id", auth, comCtrl.deleteComment);
和 App.js:
app.use("/api", postRoutes);
app.use("/api/comments", comRoutes);
為了獲得帖子的所有評論,評論控制器:
exports.getPostComments = async (req, res) => {
const { PostId } = req.params.id;
Comment.findAll({
where: {
PostId: PostId,
},
order: [["createdAt", "DESC"]],
include: [
{
model: User,
attributes: ["id", "firstName", "lastName", "imageUrl"],
},
],
order: [["createdAt", "ASC"]],
})
.then((comment) => {
res.status(200).send(comment);
})
.catch((err) =>
res.status(500).send({
err,
})
);
};
在 Postman 中創建新評論(例如,我有一個 id 為 28 的帖子,并通過在“http://localhost:8000/api/comments/28”上發出帖子請求,創建了評論并且確實與 Post 相關),但使用相同的 URL 發出 GET 請求以獲取此 Post 的所有評論,我收到錯誤 404。
我做錯了什么?
控制器看起來不錯,但根據我的發現,將“/:id”放在我的路由中的任何地方都是一種不好的做法,但是當我將它更改為“/:PostId”時,它什么也不做。
uj5u.com熱心網友回復:
router.post("/:id", auth, comCtrl.createComment); router.post("/:id", auth, comCtrl.getPostComments); router.post("/:id", auth, comCtrl.deleteComment);
router.post為 POST 請求注冊一個處理程式。
當您收到 HTTP POST 請求時,/api/comments/28它會由comCtrl.createComment.
如果comCtrl.createCommentthen 呼叫next(第三個引數)——盡管我假設它沒有,因為你沒有嘗試撰寫中間件——然后它會沿著處理程式串列傳遞給下一個匹配項(comCtrl.getPostComments)。
當您收到 HTTP GET 請求時,因為/api/comments/28您沒有呼叫,所以沒有處理程式router.get(),因此您會收到 404 錯誤。(這應該是 405 錯誤,但將其歸結為我不同意的 Express 設計決定)。
如果你想處理 GET 請求,那么你需要撰寫代碼來說明收到 GET 請求時要做什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525203.html
標籤:节点.js表示后端
