Express Router undefined params with router.use wh

2019-01-18 18:36发布

问题:

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.

回答1:

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