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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With