Subroutes in Node JS

Asked

Viewed 46 times

0

I have the following doubt.

I have two GET routes, and the second route, whenever I try to access, the browser understands as if I were informing the parameter :id and creates an error.

routes.get('/tasks/:id', TaskController.show);
routes.get('/tasks/pending', TaskController.pendingTasks);

Is there any way around this without me changing the Source /tasks ?

1 answer

1


Express checks the routes in the order they were registered, and the first that checks the condition receives the link. That is, it will check tasks/:id first and being that /:id is generalist he will ignore /pending.

There are two solutions, the simplest is to change the order. Register /pending first.

routes.get('/tasks/pending', TaskController.pendingTasks);
routes.get('/tasks/:id', TaskController.show);

The second is to call TaskController.pendingTasks inside TaskController.show, or at least from /tasks/:id... for example:

routes.get('/tasks/:id', (req, res) => {
  const id = req.params.id;
  if (id === 'pending'){
    TaskController.show
  } else {
    TaskController.pendingTasks
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.