首页 > 解决方案 > Node js express 路由冲突问题

问题描述

在我的节点 js 应用程序中,我有以下路线。

router.get('/:id', [auth], asyncHandler(async (req, res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));

router.get('/all', [auth], asyncHandler(async (req, res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));

在这里,当我调用 post/all 路由时,它会崩溃。它说,模型“Post”的路径“_id”的值“all”转换为 ObjectId 失败,模型“Post”的路径“_id”的值“all”转换为 ObjectId 失败

但如果我评论第一条路线,第二条路线完美。为什么会这样?

标签: node.jsexpress

解决方案


那是因为/all也匹配/:id。你需要做的是移到/all上面/:id

// Match this first
router.get('/all', [auth], asyncHandler(async (req, res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));

// Then if not /all treat route as the variable `id`
router.get('/:id', [auth], asyncHandler(async (req, res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));

推荐阅读