在我的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”的
但是,如果我评论第一条路线,第二条路线就可以完美地工作。为什么会这样?
答案 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);
}));`