Skip to content

Express router.param

TIP

为路由参数添加回调触发器,其中 name 为参数名称,callback 为回调函数。

Express
router.param(name, callback)

为路由参数添加回调触发器,其中 name 为参数名称,callback 为回调函数。

回调函数的参数为​​:

  • req,请求对象。
  • res,响应对象。
  • next,表示下一个中间件函数。
  • name,参数的值。
  • 参数的名称。
:::danger 与 app.param() 不同,router.param() 不接受路由参数数组。 ::: 例如,当 :user 出现在路由路径中时,您可以映射用户加载逻辑以自动将 req.user 提供给路由,或对参数输入执行验证。 ```Express router.param('user', (req, res, next, id) => { // try to get the user details from the User model and attach it to the request object User.find(id, (err, user) => { if (err) { next(err) } else if (user) { req.user = user next() } else { next(new Error('failed to load user')) } }) }) ``` 参数回调函数在定义它们的路由上是本地的。它们不会被安装的应用程序或路由继承。因此,在 router上定义的参数回调将仅由在 router路由上定义的路由参数触发。

一个参数回调在请求-响应周期中只会被调用一次,即使该参数在多个路由中匹配,如下例所示

Express
router.param('id', (req, res, next, id) => {
  console.log('CALLED ONLY ONCE')
  next()
})

router.get('/user/:id', (req, res, next) => {
  console.log('although this matches')
  next()
})

router.get('/user/:id', (req, res) => {
  console.log('and this matches too')
  res.end()
})

在 GET /user/42上,打印以下内容:

Express
CALLED ONLY ONCE
although this matches
and this matches too