有条件地使用中间件根据请求参数expression

我正在尝试根据请求查询参数来决定使用哪个中间件。

在主模块中,我有这样的东西:

app.use(function(req, res){ if (req.query.something) { // pass req, res to middleware_a } else { // pass req, res to middleware_b } }); 

middleware_amiddleware_b都是由express()函数创build的快速应用程序 ,而不是普通的中间件函数( function(req, res, next)

找不到办法做到这一点

连接/expression“中间件”并不是什么神奇的东西:它们只是function – 您可以调用它们,就像调用任何其他function一样。

所以在你的例子中:

 app.use(function(req, res, next){ if (req.query.something) { middlewareA(req, res, next); } else { middlewareB(req, res, next); } }); 

也就是说,可能有更多优雅的方法来构build分级快递应用程序。 看看TJ的video

我不会使用中间件 – 而是在中间件A和B中检查:

 //Middleware A app.use(function(req, res){ // If it doesn't match our condition then send to next middleware if (!req.query.something) { next(); } else { // We're good - let this middleware do it's thing ... next(); } }); 

与中间件B相同

 //Middleware B app.use(function(req, res){ if (req.query.something) { ... }); 

我知道这个问题是旧的,但我想分享我的解决scheme。 我通过使用callback函数返回中间件来解决这个问题。

示例中间件:

 function isAdminUser(callback){ return function(req, res, next){ var userId = callback(req); // do something with the userID next(); } } 

然后,您可以在快速路由器对象中执行以下操作

 app.use(isAdminUser(function(res){ return res.body.userId }); 

我知道我对这个线程有点迟,但是你可以使用这个插件Express Conditional Tree Middleware 。

它允许你组合多个asynchronous中间件。 具体来说,您可以创build两个代表中间件(middleware_a,middleware_b)的类,并将驻留在这些类中的applyMiddleware方法内部返回由您的中间件function创build的承诺或自定义已解决的承诺以及您的中间件function的结果。

然后在你的主要js文件中,你可以根据你的需要创build一个chainer来有条件地结合这些中间件! 查看文档了解更多信息,查看代码后会更清楚。

看起来你可能错过了这个诀窍。 每个中间件都是一个请求处理程序。 您首先查看第一个请求处理程序,然后查看下一个请求处理程序,依此类推。

以下是中间件基本的样子:

 function myFunMiddleware(request, response, next) { // Do stuff with the request and response. // When we're all done, call next() to defer to the next middleware. next(); } 

我build议你修改你的代码到这样的东西。

 app.use(function(request, response, next) { if (request.url == "/") { response.writeHead(200, { "Content-Type": "text/plain" }); response.end(".. Any custom msg..\n"); // The middleware stops here. } else { next(); }}); 

请通过本教程 ,我相信你会得到一个很好的使用中间件的概述。 有一个快乐的编码。