Brad Ross
Brad Ross

Reputation: 461

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

Upvotes: 5

Views: 8892

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

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

Upvotes: 10

a10y
a10y

Reputation: 328

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.

Upvotes: 5

Related Questions