我想将一系列app.use()
调用移入其自己的模块中。封装这个最简单的方法是在出口中公开一个function(app)
,但我觉得交给app
对象是一个不透明的接口太多。Express:撰写中间件
我想从模块外部公开一个中间件app.use()
'd。我需要链接/撰写内部使用的中间件。
有没有一种时尚的方式做到这一点,或替代?最简单的方法是什么?任何我应该避免的?
我想将一系列app.use()
调用移入其自己的模块中。封装这个最简单的方法是在出口中公开一个function(app)
,但我觉得交给app
对象是一个不透明的接口太多。Express:撰写中间件
我想从模块外部公开一个中间件app.use()
'd。我需要链接/撰写内部使用的中间件。
有没有一种时尚的方式做到这一点,或替代?最简单的方法是什么?任何我应该避免的?
纵观Express(和它所基于的Connect)的代码,看起来在一块中间件上调用use
并不会以任何方式通知任何事情,所以确实没有办法提前编写任何事情而不通过app
。然而,您可以在运行时间进行组合,例如,第一次调用中间件时,组合一些函数并缓存/调用它们。
这是我的看法:
// app.js
...
app.use(require('./middleware')());
...
// middleware.js
var express = require('express');
module.exports = function() {
var middleware = [
// list of middleware that you want to have performed:
function mymiddleware(req, res, next) {
console.log('hello world');
next();
},
express.logger('dev'),
express.cookieParser(),
express.static(__dirname)
];
return function(req, res, next) {
(function iter(i, max) {
if (i === max) {
return next();
}
middleware[i](req, res, iter.bind(this, i + 1, max));
})(0, middleware.length);
};
};
如果您需要在您的自定义中间件访问的应用程序,你可以通过req.app
或res.app
访问它。