gpt4 book ai didi

javascript - PassportJS/Express 内部出错后如何重定向?

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:21 24 4
gpt4 key购买 nike

使用 Express 和 NodeJS 配置 Passport 时,如果用户的电子邮件地址无效,我会抛出错误。出现此错误后,我想重定向到失败页面,向他们提供有关如何正确登录的说明。有更好的方法吗?如果没有,我将如何以某种方式捕获错误并重定向到新页面。

passport.use(new GoogleStrategy({
clientID : auth.googleAuth.clientID,
/* Settings redacted for brevity */
},
function(token, refreshToken, profile, done) {
User.findOne(
{
"google.id" : profile.id
},
function(err, user) {

if (err) return done(err)

if (user) return done(null, user)

else {

if (email.indexOf("lsmsa.edu") > -1) {

// Code redacted for brevity

} else {
done(new Error("Invalid email address"))
}
}
}
)
}))

最佳答案

我认为你可以使用这个:

Redirects

A redirect is commonly issued after authenticating a request.

app.post('/login',
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));

In this case, the redirect options override the default behavior. Uponsuccessful authentication, the user will be redirected to the homepage. If authentication fails, the user will be redirected back to thelogin page for another attempt.

或者这个:

Custom Callback

If the built-in options are not sufficient for handling anauthentication request, a custom callback can be provided to allow theapplication to handle success or failure.

app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});

请阅读文档: https://www.passportjs.org/concepts/authentication/downloads/html/#middleware

关于javascript - PassportJS/Express 内部出错后如何重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31601281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com