3

I'm developing a REST API using expressjs. I've two api endpoints as below:

router.get('/probe/:id', function() {});
router.get('/:id', function() {});

Now, when I call the first endpoint, the second endpoint is also called(with id as 'probe').
How can I make sure that only the first one is called? I've defined them in the order as shown above.

EDIT
I was indeed calling next() in one of the else of my conditions.
Now, I've a new bug. When I call the endpoint /probe/ - means there is no id then only the second route is called and the first route is never called.
This the only time my code fails now.
What am I missing here?

hbagdi
  • 485
  • 6
  • 18
  • What are you doing inside that first function? are you calling `res.end();` or maybe have a `next();` somewhere? – Sergio Jan 15 '16 at 16:52
  • Check to see if you have `next()` in your first route, if it is in there `next()` tells express to continue with any other matching routes (which is why it will trigger two routes). See [here](https://stackoverflow.com/questions/10695629/what-is-the-parameter-next-used-for-in-express) for a more detailed explanation. – Ash Jan 15 '16 at 16:53
  • I'm calling `res.json()` which calls `res.end();` – hbagdi Jan 15 '16 at 17:00
  • are you using any other middleware with the webapp? – Hurricane Hamilton Jan 15 '16 at 17:13
  • 1
    I was calling `next()` in one of my conditions which caused the said behaviour. I'm sorry for the confusion. – hbagdi Jan 15 '16 at 17:15

1 Answers1

0

It is recommended that you use router.route to define your routes in order to avoid duplicate route names. You'll need to refactor your code like so:

router.route('/:id')
  .get(function() {});

router.route('/probe/:id')
  .get(function() {});

It is also recommended that you serve your REST API from an /api endpoint.

app.use('/api', router);
gnerkus
  • 11,357
  • 6
  • 47
  • 71