中间件是Connect 的基础,Express 正是基于该基础。简而言之,它允许您将传入 HTTP 请求和响应的多个处理程序链接在一起。您在 Express 应用程序中为每个 app.use() 提供的参数基本上是一个“中间件”,并且是具有以下签名的回调 function (request, response, next),其中 next 是链中要调用的下一个中间件回调。以下都是中间件(最后一个是error handler,有4个参数签名):
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(function(err, req, res, next){
// logic
next();
});
就从 Express 2 到 3.x 的迁移而言,迁移具体是:
app.dynamicHelpers()(使用中间件+res.locals)
因此,举一个人为的例子,您之前可能在外部 js 文件中有一个辅助函数,而 required 将它用于您的 dynamicHelper:
//helpers.js
exports.dynamicHelpers = {
currentUser: function(req, res) {
return req.user;
}
};
// app.js
var helpers = require('./helpers').dynamicHelpers;
app.dynamicHelpers(helpers);
通过一些重组,您现在可以执行以下操作:
//locals.js
exports.setLocals = function(req, res, next){ //<- middleware function
res.locals.currentUser = req.user;
res.locals.otherVariable = ...;
next();
}
//app.js
var locals = require('./locals').setLocals;
...
app.use(locals);
这是一个很好的blog,对中间件与 pre-3.x Express 中的dynamicHelpers 进行了对比,但概念是相同的。唯一的区别是文章中使用的res.local(name, value) 现在是deprecated 用于res.locals.name = value 或res.locals({ name: value })