meh39
meh39

Reputation: 33

Express route with params followed by route without params

I have 2 routes on the following structure:

router.get('/person/:id')

router.get('/person/friends')

The request: GET /person/1 is being handled by the first route by the order that I wrote them.

this order:

router.get('/person/:id')

router.get('/person/friends')

will go to '/person/:id

while this one:

router.get('/person/friends')

router.get('/person/:id')

will go to '/person/friends'

Am I using the format for params wrong? isn't :id means that it expects a variable, while /friends expect the same string "friends" ?

Upvotes: 1

Views: 663

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30725

You can use a regular expression for this purpose, to filter paths, e.g.

app.get("^/person/:id([0-9]{1,6})", function(req, res, next){
    console.log('/person/:id endpoint hit: id: ' + req.params.id);
    res.end('OK');
});

app.get("/person/friends", function(req, res, next){
    console.log('/person/friends endpoint hit');
    res.end('OK');
});

This will mean that any requests like: http://localhost:3000/person/42 will go to the :/id handler and requests like http://localhost:3000/person/friends will go to the /friends handler. You can change the regex as you like, I've assumed a 1 to 6-digit number for the ID.

You could make this more permissive to allow any amount of digits by doing something like:

app.get("^/person/:id([0-9]+)", function(req, res, next){
    console.log('/person/:id endpoint hit: id: ' + req.params.id);
    res.end('OK');
});

If you don't specify a regex pattern, the request /person/friends will match the /person/:id handler and you'll get this in your logs:

/person/:id endpoint hit: id: friends

Upvotes: 2

Related Questions