Node.js-中间件中的res.redirect问题 [英] Node.js - Issue with res.redirect in middleware

查看:164
本文介绍了Node.js-中间件中的res.redirect问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在加载所有页面之前使用authenticateUser()中间件.我没有在每次调用中都包含它(例如在app.get('/',authenticateUser,function()...)中),而是尝试在调用app.use(app.router)之前使用app.use(authenticateUser)进行设置. ).

I'm trying to use a authenticateUser() middleware before loading all of my pages. Instead of including it in each call (as in app.get('/', authenticateUser, function()...)), I tried setting it with app.use(authenticateUser) right before calling app.use(app.router).

但是,这没有用. authenticateUser基本上是:

This didn't work, however. authenticateUser is basically:

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;

And then in app.get('/login') I set req.session.loginFailed to be false;

这应该可以,但是我只想在我的实际页面之一的app.get()或app.post()等上调用它.我认为它多次调用许多不同的请求(因为加载一页后,多次调用将loginFailed设置为true")

This should work, but I only want to call it on an app.get() or app.post() etc. for one of my actual pages. I think its getting called lots of times for many different requests (because upon loading one page, 'setting loginFailed to true' is called many times)

是否有更好的方法可以做到这一点?还是应该在网站上的每个页面之前简单地调用它?

Is there a better way to do this? Or should I simply be calling it before every page on my site?

推荐答案

我认为您正在进行过多的检查.只有一条路由可以处理用户登录(检查用户名和密码,如果成功,则将用户名存储在会话中),并且应该仅在需要认证的路由(不是全部)上分配认证中间件.

You are doing way too many checks out there in my opinion. Only one route should handle user login (check for user & pass, and store the username in the session if succeeded) and you should assign the auth middleware only on the routes that require auth (not all).

我提供了一个简化的示例,以便您理解我的观点:

I've put up a simplified example so you can understand my point:

登录路径

app.post('/login', function (req, res) {
  var variables_set = (req.body.user && req.body.pass);
  if (variables_set && (req.body.user === 'username') && (req.body.pass === 'password')) {
    req.session.username = req.body.user;
  } else {
    res.redirect('/login?failed=true'); 
  }
});

身份验证中间件

if (!req.session.username) {
  res.redirect('/login');
} else {
  next();
}

您可以在Alex Young的Nodepad应用程序中看到一个更完整的示例: https://github.com/alexyoung /nodepad (此处为该应用程序的教程: http://dailyjs.com/tags.html# lmawa )

You can see a more complete example in action in Alex Young's Nodepad application: https://github.com/alexyoung/nodepad (tutorials for that app here: http://dailyjs.com/tags.html#lmawa )

这篇关于Node.js-中间件中的res.redirect问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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