Shashika Virajh
Shashika Virajh

Reputation: 9457

Node js express route conflict issue

In my node js application, I have the following routes.

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);
}));

Here, when I call the post/all route, it gets crashed. It says, Cast to ObjectId failed for value "all" at path "_id" for model "Post"Cast to ObjectId failed for value "all" at path "_id" for model "Post"

But if I comment the first route, second one works perfectly. Why is this happening?

Upvotes: 1

Views: 659

Answers (2)

Ankur Patel
Ankur Patel

Reputation: 488

because when you call /all route it will redirect to /:id route and try to convert all to objectId. so you need to change your route like this

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);
}));`

Upvotes: 1

slebetman
slebetman

Reputation: 113876

That is because /all also matches /:id. What you need to do is move /all above /: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);
}));

Upvotes: 3

Related Questions