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',res) => {
  const posts = await postService.getallPosts(req.user.id);
  res.json(posts);
}));

在这里,当我呼叫发布/所有路线时,它崩溃了。它说,对模型“ Post”的路径“ _id”的值的,对ObjectId的转换失败对模型“ Post”的路径“ _id”的值“ all”的对对象ID的“对象”广播失败

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

zhuguanglu 回答:Node JS Express路由冲突问题

那是因为/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',res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));
,

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

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

router.get('/all',res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));`
本文链接:https://www.f2er.com/3160949.html

大家都在问