Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express Router undefined params with router.use when split across files

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.

like image 886
whitfin Avatar asked Mar 11 '15 01:03

whitfin


1 Answers

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

like image 184
loganfsmyth Avatar answered Oct 20 '22 23:10

loganfsmyth