首页 > 解决方案 > 在 Node.js Express 和 Passport.js 身份验证后 res.redirect 不起作用

问题描述

我在使用 res.redirect() 进行页面重定向时遇到问题。

这是我的代码片段。

console.log('user=', req.user);- 这是有效的。在此之后,页面正在加载,但仍在加载中。发生超时错误。

res.redirect('/chat/loginsuccess');- 这行不通。

有没有人遇到过这个问题?请帮我。

...
router.post('/login', passport.authenticate('chat-login'), function(req, res, next) {
    console.log('user=', req.user);
    return res.redirect('/chat/loginsuccess');
});

...
passport.use('chat-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password'
}, function(email, password, done) {
    if (email) {
        // Use lower-case e-mails to avoid case-sensitive e-mail matching
        email = email.toLowerCase();
    }

    // asynchronous
    process.nextTick(function() {
        ChatUser.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err) {
                return done(err);
            }

            // if no user is found, return the message
            if (!user) {
                return done(null, false, { message: 'No User Found.' });
            }

            if (!user.validPassword(password)) {
                return done(null, false, { message: 'Oops! Wrong Password.' });
            }

            // success
            return done(null, user);
        });
    });

}));
...

标签: javascriptnode.jsexpresspassport.js

解决方案


您可以简单地使用护照的 successRedirect 和 failureRedirect 选项。

您的登录路线将类似于:

router.post('/login', passport.authenticate('chat-login', {
                                             successRedirect : '/whereEverYouWantIfsuccessfullyLoggedIn',
                                             failureRedirect : '/whereEverYouWantIffailedToLogIn'
}));

推荐阅读