你可以在Node.JS Express应用程序中插入中间件

有没有办法在Express堆栈中注入中间件? 我的意思是我想让我的app.js设置主要的中间件链,然后调用其他模块传递应用程序实例,他们可能想要插入更多的中间件(例如一个authentication模块,想在正确的地方添加护照)

您当然可以将您的app对象传递给其他模块并在那里调用。 当然,中间件function是按照它们添加的顺序来执行 ,所以你必须非常小心,确保你按照正确的顺序调用。

app.js

 var app = express(); // ... app.use(express.logger()); // first middleware function var someOtherModule = require('./mod.js'); someOtherModule.init(app); app.use(express.static()); // last middleware function) 

mod.js

 exports.init = function(app) { app.use(function(req, res, next) { }); }; 

就实际上在堆栈中间注入一个中间件函数(在你已经用一组中间件函数调用了app.use之后),没有文档说明的方法。 use只添加一个函数到堆栈的末尾。

use实际上由Connect在proto.js中提供 :

 app.use = function(route, fn){ ... this.stack.push({ route: route, handle: fn }); return this; }; 

从技术上讲 ,你可以自己摆弄app.stack ,但我不会这样做 。 你会搞乱一个没有logging的实现细节,这个细节很容易改变。 换句话说,未来的Connect或Express更新可能会破坏您的应用程序。

你可以使用app.use(fn)或者像这样堆叠它们:

 app.get('/foo', fn1, fn2, fn3); 

签名必须始终相同,并调用next();

 function(req, res, next) { next(); } 

我不明白是什么问题?

您可以在中间件中添加任何function:

 app.use(function(req,res,next){ //some munipulation with req and res next() }) 

你可以发送这个app到你的模式