简体   繁体   中英

Why app.param not work if I specify a router.param in Express

All:

I am pretty new to Express.js, when I tried .param(), one interesting thing is:

In app.js ( the main server file), I have something like:

app.param("id", function(req, res, next, id){
  console.log(id+" in app level");
  next();
})
app.use("/", routes);

The app is the Express Application object, and in routes Router module:

router.param("id", function(req, res, next, id){
    console.log(id + " in router level");
    next();
})

router.get('/:id', function(req, res, next) {
  res.send('respond with a resource');
});

But when I request /testUserId, only the param() inside the router module runs, I thought app.param() will run first then router.param(), but it is actually not, could anyone help explain why( I must miss some parts of the API document from Express ) and how to make both run?

Thanks

I agree that this is somewhat confusing. There was conversation about this, and issue was opened to clarify this behavior in documentation ( Explain that .param doesn't get inherited in mounted routers. ).

Here is latest explanation: app.param([name], callback)

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on app will be triggered only by route parameters defined on app routes.

To recap, behavior that you see is expected. Nested 'routers' or 'apps' do not inherit .param() from parent app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM