Can not get req.params in router middleware

// hasProjectPremission List this
hasProjectPremission = (req, res, next) => {
  console.log(req.params); // {}
  next();
}
router.use(apiBiz.hasProjectPremission);
router.post('/:projId/api/new', apiBiz.createApi); 

When request to the create api, I can’t get req.params in hasProjectPremission, it’s an empty object({})。

Author: Fantashit

1 thought on “Can not get req.params in router middleware

  1. Actually middleware can get parameters from router, but it needs to know which one.

    for example:

    // handle any additional path with optional catch all
    router.use('/:projId(\\d+)(/*)?', (req, res, next) => { 
      console.log(req.params); // { '0': undefined, '1': undefined, projId: '1337' }
    
      next();
    });
    
    router.post('/:projId(\\d+)/api/new', (req, res) => res.sendStatus(200))

    But IMO you should use router.param which will act like an middleware, executed right before route is handled.

    router.param('projId', (req, res, next, projId) => {
      // executes before route handler
    
      next();
    });
    
    router.post('/:projId/api/new', (req, res) => res.send(req.params.projId)) // 1337

Comments are closed.