【问题标题】:Express Passport failureRedirect not working快速护照失败重定向不起作用
【发布时间】:2017-08-20 14:05:25
【问题描述】:

我设置了local 策略,但failureRedirect 似乎无法正常工作。当发生连接错误时(例如数据库的 URL 错误),响应是错误 500,而不是重定向到指定的路由。

这是我的路线代码:

router.route('/login')
    .post(passport.authenticate('local', {
        failureRedirect: '/' 
    }), function(req, res){ 
        console.log('user logged in');
        res.redirect('../console');
    });

这是我对local 策略的实现:

module.exports = function(){
    passport.use(new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    },
        function(email, password, done){
            pg.defaults.ssl = true;
            pg.connect(process.env.DATABASE_URL, function(err, client) {
                if (err){
                    console.log('Connection issue when logging in: ' + JSON.stringify(err));
                    done('Error with database,', null); // this is the problem area!!!
                } else {
                    client
                        .query(`SELECT * FROM agent WHERE email='${email}'`, function(err, result) {
                            if(err || result.rows.length === 0 ) {
                                console.log('Query issue when loggin in: '+ JSON.stringify(err));
                                done(null, false);
                            } else {
                                var user = result;
                                console.log('ready to log user in');
                                done(null, user);
                            }
                        });
                }
            });
        }
    ));
};

我在想也许我对done() 回调函数的使用是错误的,但我遵循了文档。感谢您的帮助。

【问题讨论】:

  • 谢谢,但没有按预期工作:它将错误打印到页面而不是重定向到failureRedirect中指定的页面
  • 酷,现在是什么错误?
  • 就像我说的,页面不会重定向到failureRedirect链接,而是停留在打印错误的按钮action的路径

标签: node.js authentication express passport.js


【解决方案1】:

我遇到的问题是,如果用户不存在,我会抛出一个错误 -- done('some error', null);,这似乎不是 Passport 所期望的。

它支持将虚假用户作为另一个失败标志的概念。因此,如果您没有找到用户,则适当的签名将是 done(null, null)

因此,当出现数据库错误时,您将“数据库错误”作为错误。你应该把null。

【讨论】:

  • 完成的参数是done(err, user, options)options可以带消息参数。所以如果有异常,通过err,如果没有用户,返回userfalse,并设置像{message: "no such user"}这样的选项
  • 每当 err 不为 null 且 user 为 false 时,我仍然会遇到问题。如果 err 设置为 null,它会起作用。 done(null,false,{message: "no such user"}) 工作正常。
【解决方案2】:

你必须

抛出新的错误('hello world')

触发失败重定向,你也可以试试

https://docs.nodejitsu.com/articles/errors/what-is-try-catch/

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2017-09-27
    • 2015-06-01
    • 2018-11-19
    • 2021-04-16
    • 2018-03-19
    • 2019-03-08
    • 2013-05-27
    • 2023-03-14
    相关资源
    最近更新 更多