我有许多类似于以下内容的中间件功能:
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);
答案 0 :(得分:3)
尝试使用以下代码
app.use('/', [validate, checkValid,respond]);
<强> OR 强>
var middleware = [validate, checkValid,respond];
app.use('/', middleware );
需要将该系列中的所有功能都作为执行要求。
由于