在所有路由中添加中间件,但只有少数几个 [英] add middleware to all routes but a few

查看:55
本文介绍了在所有路由中添加中间件,但只有少数几个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将中间件添加到所有可能的路由中,除了那些与给定表达式匹配的路由之外?

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.

推荐答案

如果您使用的是express 3.x系列,那么您不走运.您需要破解中间件来检查路径.

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
}

在express 4.0中,您可以轻松得多.

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
});

希望这能解释.

这篇关于在所有路由中添加中间件,但只有少数几个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆