Express routes parameter conditions

node.jsExpressRoutingUrl Routing

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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

Solution 3 - node.js

You can use:

// /12345
app.get(/\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});

or this:

// /post/12345
app.get(/\/post\/([^\/]+)\/?/, function(req, res){
  var id = req.params[0];
  // do something
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1082754View Question on Stackoverflow
Solution 1 - node.jsdanmactoughView Answer on Stackoverflow
Solution 2 - node.jsMarius KjeldahlView Answer on Stackoverflow
Solution 3 - node.jsMarco GodínezView Answer on Stackoverflow