Express Passport failureRedirect 不工作
Express Passport failureRedirect not working
我设置了 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()
回调函数的使用是错误的,但我遵循了文档。感谢您的帮助。
你必须
throw new Error('hello world')
触发失败重定向,您也可以尝试
https://docs.nodejitsu.com/articles/errors/what-is-try-catch/
我遇到的问题是,如果用户不存在,我会抛出一个错误 -- done('some error', null);
这似乎不是 Passport 所期望的。
它支持将虚假用户完成作为失败的另一个标志的概念。因此,如果您找不到用户,适当的签名将是 done(null, null)
。
所以当出现数据库错误时,您将 'Error with database' 作为错误。你应该放空。
我设置了 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()
回调函数的使用是错误的,但我遵循了文档。感谢您的帮助。
你必须
throw new Error('hello world')
触发失败重定向,您也可以尝试
https://docs.nodejitsu.com/articles/errors/what-is-try-catch/
我遇到的问题是,如果用户不存在,我会抛出一个错误 -- done('some error', null);
这似乎不是 Passport 所期望的。
它支持将虚假用户完成作为失败的另一个标志的概念。因此,如果您找不到用户,适当的签名将是 done(null, null)
。
所以当出现数据库错误时,您将 'Error with database' 作为错误。你应该放空。