Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression in Node.js Express Router

I have tried to find a way to enter regular expression into an express routing URL and then access the variable portion of the URL through the request object. Specifically I want to route to the url "/posts/" + any number of digits. Is there a way to do this?

Examples:

/posts/54
/posts/2
/posts/546
like image 414
Brad Ross Avatar asked Dec 11 '22 23:12

Brad Ross


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 digits

like image 115
JohnnyHK Avatar answered Jan 09 '23 02:01

JohnnyHK


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

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

You should also check out the express documentation: http://expressjs.com/api.html. The request section would probably prove quite useful to you.

like image 40
a10y Avatar answered Jan 09 '23 03:01

a10y