【问题标题】:cannot DELETE post (express mongoose postman)无法删除帖子(快递猫鼬邮递员)
【发布时间】:2021-06-16 23:21:31
【问题描述】:

我正在尝试使用 http://localhost:5000/posts/60c9b65463cdb804e4238257 上的 Postman 请求执行简单的 REST 操作,但使用 DELETE 时出现此错误:

404 not found Cannot DELETE /posts/60c8e5a860b84f0013a1d9d7

我会很高兴任何提示。

https://i.stack.imgur.com/PL9P8.jpg

// index.js

app.use(express.json());
app.use(cors());

app.use("/posts", postRoutes);

//routes.js

const routes = express.Router();

routes.get("/", getPosts);
routes.post("/", createPost);
routes.patch("/:id", updatePost);
router.delete("/:id", deletePost);
export default routes;

// controller.js

export const deletePost = async (req, res) => {
  const { id } = req.params;

  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send(`No post with id: ${id}`);

  try {
    await Bootcamp.findByIdAndDelete(id);

    res.json({ message: "Post deleted successfully.",success:true });
  } catch (error) {
    res.status(500).json({ success: flase, message: error.message });
  }
};

export default router;

【问题讨论】:

  • 并且 _id 为 60c8e5a860b84f0013a1d9d7 的文档存在于 bootcamps 集合中?
  • 是的,我尝试过使用其他文档并且有同样的错误,只是 diff id tho
  • 奇怪,也许这能帮上忙? stackoverflow.com/questions/61418553/…
  • 我在看,但我不明白为什么 PATCH 没有问题,而类似的 DELETE 会这样做....
  • 问题不在于猫鼬或任何数据库 - 在于路由器以及您发送请求的方式。请向我们显示邮递员请求代码,否则我们无法为您提供帮助:)

标签: node.js express postman


【解决方案1】:

您在delete 路由器线路中漏掉了一个“s”。


const routes = express.Router();

routes.get("/", getPosts);
routes.post("/", createPost);
routes.patch("/:id", updatePost);
router.delete("/:id", deletePost); // maybe it should be "routes"
export default routes;

-> routes.delete("/:id", deletePost);

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 2011-08-28
    • 2018-10-12
    • 2020-08-14
    • 2020-03-26
    • 2021-04-12
    • 2021-04-11
    • 2016-03-23
    • 1970-01-01
    相关资源
    最近更新 更多