[英]res.redirect not working after Node.js Express & Passport.js authentication
I have a problem with page redirect with res.redirect(). 我使用res.redirect()进行页面重定向时遇到问题。
Here's my code snippet. 这是我的代码段。
console.log('user=', req.user);
- This is working. -工作正常。 After this, page is loading but still in loading.
此后,页面正在加载,但仍在加载。 Timeout error occurs.
发生超时错误。
res.redirect('/chat/loginsuccess');
- This isn't working. -这不起作用。
Does anyone experience this issue before? 有人以前遇到过这个问题吗? Please help me.
请帮我。
...
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);
});
});
}));
...
You can simply use the successRedirect and failureRedirect options of passport. 您可以简单地使用通行证的successRedirect和failureRedirect选项。
Your login route will look something like: 您的登录路线如下所示:
router.post('/login', passport.authenticate('chat-login', {
successRedirect : '/whereEverYouWantIfsuccessfullyLoggedIn',
failureRedirect : '/whereEverYouWantIffailedToLogIn'
}));
I fixed this problem. 我解决了这个问题。 The problem was in
passport.deserializeUser()
. 问题出在
passport.deserializeUser()
。
Here's my passport.deserializeUser()
code snippet. 这是我的
passport.deserializeUser()
代码段。
-Old code -旧代码
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
if (user != null) {
done(null, user);
} else {
User.findById(id, function(err, admin) {
if (user != null) {
done(null, user);
}
});
}
});
});
-Updated code -更新代码
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
if (user != null) {
done(null, user);
} else {
ChatUser.findById(id, function(err, admin) {
done(err, admin);
});
}
});
});
The problem is that when user is null, there was no done()
. 问题是当user为null时,没有
done()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.