我想在我的网络应用程序用户输入网址时检查他们的授权。但是当我使用单独的中间件来检查授权时,它对于已经存在的路由是没有用的,例如:
function authChecker(req, res, next) {
if (req.session.auth) {
next();
} else {
res.redirect("/auth");
}
}
app.use(authChecker);
app.get("/", routes.index);
app.get("/foo/bar", routes.foobar);
authChecker 无法检查输入这两个网址的用户的权限。 它仅适用于未指定的 url。
我看到了一种方法,我可以将 authChecker 放在路由和路由处理程序之间, 如:
app.get("/", authChecker, routes.index);
但是我怎样才能以一种简单的方式来实现它,而不是把 authChecker 放在每条路线上呢?
最佳答案
只要
app.use(authChecker);
在
之前app.use(app.router);
每个请求都会调用它。但是,您会得到“重定向过多”,因为它被 ALL ROUTES 调用,包括 /auth。所以为了解决这个问题,我建议将函数修改为:
function authChecker(req, res, next) {
if (req.session.auth || req.path==='/auth') {
next();
} else {
res.redirect("/auth");
}
}
这样您也不会重定向到身份验证网址。
关于node.js - express 进入每条路由前如何使用中间件检查授权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700729/