Express routes parameter conditions


Question

I have a route on my Express app that looks like this:

app.get('/:id', function (request, response) {
  …
});

The ID will always be a number. However, at the moment this route is matching other things, such as /login.

I think I want two things from this:

  1. to only use this route if the ID is a number, and
  2. only if there isn't a route for that specific paramater already defined (such as the clash with /login).

Can this be done?

1
64
11/13/2015 6:53:32 PM

Accepted Answer

Expanding on Marius's answer, you can provide the regex AND the parameter name:

app.get('/:id(\\d+)/', function (req, res){
  // req.params.id is now defined here for you
});
126
4/12/2013 2:31:11 PM

Yes, check out http://expressjs.com/guide/routing.html and https://www.npmjs.com/package/path-to-regexp (which express uses). An untested version that may work is:

app.get(/^(\d+)$/, function (request, response) {
  var id = request.params[0];
  ...
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon