gpt4 book ai didi

node.js - 将中间件添加到除少数之外的所有路由

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:20 25 4
gpt4 key购买 nike

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

我知道如何向与表达式匹配的中间件添加中间件:

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

但我想要求在所有路由中登录,除了少数在其路径中具有特定前缀的路由。

最佳答案

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

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

希望这能解释。

关于node.js - 将中间件添加到除少数之外的所有路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com