Regular expression in Node.js Express Router

I tried to find a way to enter the regular expression in the direct routing URL, and then access the variable part of the URL through the request object. In particular, I want to forward the URL "/ posts /" + any number of digits. Is there any way to do this?

Examples:

/posts/54 /posts/2 /posts/546 
+4
source share
2 answers

This should do it:

 app.get('/posts/:id(\\d+)', function(req, res) { // id portion of the request is available as req.params.id }); 

EDIT : added regex to path to limit it to numbers

+9
source

I agree with Johnny, my only addition is that you can do this for any number of levels. For instance:

 app.get('/users/:id/:karma', function(req, res){ //Both req.params.id and req.params.karma are available parameters. }); 

You should also check the express documentation: http://expressjs.com/api.html . The query section is likely to be very useful for you.

+4
source

All Articles