Node JS Express路由冲突问题

时间:2019-11-05 09:12:08

标签: node.js express

在我的node 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”的路径“ _id”的值的,对ObjectId的转换失败对模型“ Post”的路径“ _id”的值“ all”的对对象ID的“对象”广播失败

但是,如果我评论第一条路线,第二条路线就可以完美地工作。为什么会这样?

2 个答案:

答案 0 :(得分:2)

那是因为/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);
}));

答案 1 :(得分:1)

因为当您调用/ all route时,它将重定向到/:id route并尝试将其全部转换为objectId。所以你需要像这样改变路线

router.get('/one/: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);
}));`