Node js太多使用中间件重定向的重定向 [英] Node js too many redirect using middleware redirect

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

问题描述

在我的 Node.js 应用程序中(我使用的是 express 4.x),我想检查用户是否已登录.如果用户没有登录,我想重定向到我的登录页面.然后我在中间件中这样做:

In my Node.js application (I'm using express 4.x) I want to check if the user is logged. If the user isn't logged I want to redirect to my login page. Then I do that in the middleware like this :

Server.js

app.use(function (req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/login');
});

登录途径

// Login page
app.get('/login', function(req, res){
    res.render('pages/login', {
                error   : req.flash('loginError'),
                info    : req.flash('info'),
                success : req.flash('success')
            });
});

但是当我在中间件中添加这段代码时,登录页面被调用了 30 多次......我的浏览器显示 Too many redirect.

But when I add this code in my middleware, the login page is called more than 30 times... And my browser says Too many redirect.

你知道为什么我的登录页面被频繁调用吗?

Do you know why my login page is called a lot ?

推荐答案

你陷入无限循环,因为如果请求的路径是 login 即使这样重定向到 login 再次

You catch in infinite loop because if the requested path is login even so redirect to login again

app.use(function (req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    if(req.route.path !== '/login')
      res.redirect('/login');
    next();
});

这篇关于Node js太多使用中间件重定向的重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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