添加中间件到所有的路线,但less数

除了与给定的expression式匹配的所有可能的路由,我怎样才能添加中间件?

我知道如何将中间件添加到匹配expression式的中间件:

app.all('/test/*', requireLogin); 

但我想要求在所有路由中login,除了less数path中有特定前缀的路由。

如果您正在使用Express 3.x系列,那么您在这里运气不佳。 你需要破解中间件来检查path。

 app.use(function(err, req, res, next){ if(canRouteSkipLogin(req.path) next(); else{ //Do the auth logic } }); canRouteSkipLogin = function(path){ //logic to find the path which can skip login } 

而在Express 4.0中,你可以做更简单的方法。

  var authRoutes = express.Router(); var nonAuthRoutes = express.Router(); authRoutes.use(function(req, res, next) { //Do Auth Logic here }); 

希望这解释。

我能做到这一点的唯一方法就是在中间件本身中用一个guard子句明确地编写代码。 所以中间件总是被调用,它检查req.path是否绕过正则expression式,如果是这样,就立即调用next()并返回。 这是expressjs body-parser (通过type-is模块)使用的模式,基于检查给定的请求不需要它们执行任何操作来禁止它们自己。