c0de
c0de

Reputation: 819

express/node.js - How to pass route parameters to other files?

Encountered a strange bug where if I have a route defined like so in routes/posts/index.js:

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

Inside ./edit, I have the endpoint defined like so:

router.post('/', passport.authenticate('jwt', { session: false}), function(req, res){

If I hit /posts/:id/edit, I successfully hit the endpoint in ./edit, but const id = req.params.id; will be undefined. However, if I define the route directly in routes/posts/index.js, req.params.id will be defined.

What is the correct way for letting the route in ./edit 'recognize' the id parameter?

Upvotes: 2

Views: 448

Answers (1)

mscdex
mscdex

Reputation: 106698

You can merge in parent router parameters by passing {mergeParams: true} to express.Router().

Upvotes: 2

Related Questions