Skip to content

Express.param

TIP

给路由参数添加回调触发器。

Express
app.param([name], callback)

给路由参数添加回调触发器,这里的name是参数名或者参数数组,function是回调方法。回调方法的参数按序是请求对象,响应对象,下个中间件,参数值和参数名。

如果name是数组,会按照各个参数在数组中被声明的顺序将回调触发器注册下来。还有,对于除了最后一个参数的其他参数,在他们的回调中调用next()来调用下个声明参数的回调。对于最后一个参数,在回调中调用next()将调用位于当前处理路由中的下一个中间件,如果name只是一个string那就和它是一样的(就是说只有一个参数,那么就是最后一个参数,和数组中最后一个参数是一样的)。

例如,当:user出现在路由路径中,你可以映射用户加载的逻辑处理来自动提供req.user给这个路由,或者对输入的参数进行验证。

Express
app.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'))
    }
  })
})

对于Param的回调定义的路由来说,他们是局部的。它们不会被挂载的app或者路由继承。所以,定义在app上的Param回调只有是在app上的路由具有这个路由参数时才起作用。

在定义param的路由上,param回调都是第一个被调用的,它们在一个请求-响应循环中都会被调用一次并且只有一次,即使多个路由都匹配,如下面的例子:

Express
app.param('id', function(req, res, next, id) {
    console.log('CALLED ONLY ONCE');
    next();
});
app.get('/user/:id', function(req, res, next) {
    console.log('although this matches');
    next();
});
app.get('/user/:id', function(req, res) {
    console.log('and this mathces too');
    res.end();
});

当GET /user/42,得到下面的结果:

TIP

CALLED ONLY ONCE
although this matches
and this matches too

Express
app.param(['id', 'page'], function(req, res, next, value) {
    console.log('CALLED ONLY ONCE with', value);
    next();
});
app.get('/user/:id/:page', function(req. res, next) {
    console.log('although this matches');
    next();
});
app.get('/user/:id/:page', function (req, res, next) {
    console.log('and this matches too');
    res.end();
});

当执行GET /user/42/3,结果如下:

TIP

CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this mathes too