如何将多个中间件功能合并为一个?

时间:2015-04-07 12:49:30

标签: javascript node.js express

我有许多类似于以下内容的中间件功能:

function validate(req, res, next) {
  req.validationError = new Error('invalid');
}

function checkValid(req, res, next) {
  if (req.validationError) {
    next(req.validationError);
  } else {
    next();
  }
}

function respond() {
  res.json({result: 'success'});
}

有没有办法将它们包装成一个函数?所以我做了类似的事情:

function respondIfValid(req, res, next) {
  // Evoke the following middleware: 

  // validate
  // checkValid
  // respond
}

app.use('/', respondIfValid);

而不是:

app.use('/', validate, checkValid, respond);

1 个答案:

答案 0 :(得分:3)

尝试使用以下代码

app.use('/', [validate, checkValid,respond]);

<强> OR

var middleware = [validate, checkValid,respond];

app.use('/', middleware );

需要将该系列中的所有功能都作为执行要求。

由于