48

I'm not sure if this is a bug in Express, or if I'm just doing something wrong (probably the latter), but I'm finding that req.params is only retaining parameters in the final step of the request. To demonstrate what I mean:

Working Example:

router.get('/:id/test', function(req, res){
    // req.params.id is not undefined
});

Doesn't Work :(

File 1:

router.use('/:id', require('./file2'));

File 2:

router.get('/test', function(req, res){
    // req.params.id is undefined?!
});

Now... the above seems totally illogical to me, seeing as the Express generator defines routes in the above way - and it must still be defined in the path somewhere. Surely I should still be able to access "id"?

So basically, am I missing something? Is this deliberate/is it documented? FWIW I'm using Express v4.12.0.

Disclaimer: the file thing is probably irrelevant, but better to be safe than sorry.

whitfin
  • 4,539
  • 6
  • 39
  • 67

1 Answers1

91

When you create your Router in File 2, you need to tell it to inherit params from parents.

var router = express.Router({mergeParams: true});

http://expressjs.com/api.html#router

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 1
    Bah, I knew it would be something simple that I looked over. Surprised I never ran into this before... Thanks for the tip ;) – whitfin Mar 11 '15 at 02:05
  • I was only able to achieve it when adding the `{mergeParams: true}` also in my main file (Express 4.13.4). Edited the answer because some people might need it. – George May 12 '16 at 23:45