문제

how can I add middleware to all possible routes except for these that match a given expression?

I know how to add a middleware to ones that match an expression:

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

but I want to require login in all routes except for a few that have a specific prefix in their paths.

도움이 되었습니까?

해결책

If you are using express 3.x series you are out of luck here. You need to hack the middle ware to to check the the 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
}

While in express 4.0 you can do it much easier way.

 var authRoutes = express.Router();
 var nonAuthRoutes = express.Router();

authRoutes.use(function(req, res, next) {
    //Do Auth Logic here
});

Hope this explains.

다른 팁

The only way I've been able to do this is to just explicitly code for it with a guard clause in the middleware itself. So the middleware always gets called, it checks req.path against the bypass regex, and if so, just calls next() immediately and returns. This is the pattern used by things like the expressjs body-parser (via the type-is module) to no-op themselves based on checking that a given request doesn't require them to do anything.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top