Express routes of parameter parameters

I have a route in my Express application that looks like this:

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

The identifier will always be a number. However, this route currently matches other things, such as /login .

I think I need two things:

  • use this route only if the identifier is a number, and
  • only if there is no longer a route for this particular parameter (for example, a collision with /login ).

Can this be done?

+48
url-routing express routing
Jun 29 '12 at 8:26
source share
3 answers

By expanding Marius's answer, you can specify the regular expression AND the parameter name:

 app.get('/:id(\\d+)/', function (req, res){ // req.params.id is now defined here for you }); 
+102
Jun 29 '12 at 10:45
source share
β€” -

Yes, see http://expressjs.com/guide/routing.html and https://www.npmjs.com/package/path-to-regexp (which expresses usage). Unverified version that may work:

 app.get(/^(\d+)$/, function (request, response) { var id = request.params[0]; ... }); 
+9
Jun 29 2018-12-12T00:
source share

You can use:

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

or that:

 // /post/12345 app.get(/\/post\/([^\/]+)\/?/, function(req, res){ var id = req.params[0]; // do something }); 
+2
Dec 29 '12 at 7:23
source share



All Articles