سؤال

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