Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express routes parameter conditions

Express routes parameter conditions

Problem

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?

Problem courtesy of: user1082754

Solution

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 courtesy of: danmactough

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express routes parameter conditions

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×