【发布时间】:2012-02-02 07:57:00
【问题描述】:
我正在尝试在加载我的所有页面之前使用 authenticateUser() 中间件。我没有在每次调用中都包含它(如 app.get('/', authenticateUser, function()...)),而是在调用 app.use(app.router) 之前尝试使用 app.use(authenticateUser) 设置它)。
但是,这不起作用。 authenticateUser 基本上是:
if (req.session.loginFailed) {
next()
else {
if (req.session.user_id) {
...
if (userAuthenticated) {
next();
} else {
req.session.loginFailed = true;
console.log('setting loginFailed to true');
res.redirect('/login');
}
}
}
然后在 app.get('/login') 我将 req.session.loginFailed 设置为 false;
这应该可以,但我只想在 app.get() 或 app.post() 等上为我的一个实际页面调用它。我认为它被许多不同的请求调用了很多次(因为在加载一个页面时,'setting loginFailed to true' 被调用了很多次)
有没有更好的方法来做到这一点?还是我应该在我网站上的每个页面之前调用它?
【问题讨论】:
标签: session node.js express middleware