Appearance
Express router.param
TIP
为路由参数添加回调触发器,其中 name 为参数名称,callback 为回调函数。
Express
router.param(name, callback)
为路由参数添加回调触发器,其中 name 为参数名称,callback 为回调函数。
回调函数的参数为:
- req,请求对象。
- res,响应对象。
- next,表示下一个中间件函数。
- name,参数的值。
- 参数的名称。
一个参数回调在请求-响应周期中只会被调用一次,即使该参数在多个路由中匹配,如下例所示
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