Passport 和 Axios 返回 Flash 消息

问题描述

我有一个 Express 应用程序,使用 Passportjs 进行身份验证并在前端使用 Reactjs,但我似乎无法弄清楚如何让 PassportJS 返回 req.flash() 或 JSON 对象,如果用户不存在或密码不匹配。

我在 React 中使用 axios 向我的 API 端点发出请求,并注意到返回了 401 错误,这与响应一致 Passport 表示它将在身份验证失败时响应,但是我如何通过这些请求传递消息,我能否区分错误原因?

错误(无用户或密码错误):

http://localhost:3000/api/auth/signin/ 401 (Unauthorized)

响应 axios 请求(在没有用户或密码错误时触发 .catch()):

axios.post('/api/auth/signin/',{ email,password },{
            headers: {
                'Content-Type': 'application/json'
            },withCredentials: true
        }).then((res) => {
            console.log(res)
            const data = res.data;
        }).then(()=> {
            // On successful sigin,redirect to /app/profile/
            router.push('/app/profile/')
        }).catch((err) => {
            console.log(err)
        })

PassportJS 配置:

passport.use(new passportLocal({ 
        passReqToCallback: true,usernameField: 'email'
    },function(req,email,password,done) {
        User.findOne({ 
            where: {
                email: email
            }
        }).then(function(user){
            console.log('user')
            if(!user){
                console.log("User not found")
                // User not found
                return done(null,false,req.flash('User does not exist in the database.'));
            } else if(!user.validPassword(password)) {
                console.log("Password is incorrect")
                // Wrong password
                done(null,req.flash("Incorrect Password"));
            } else {
                console.log("User found & password correct")
                // User found and password correct
                return done(null,user)
            }
        }).catch(function(err){
            console.log("Server error with signin")
            // Server error
            return done(null,req.flash("It looks like there was a server issue. Please try again."));
        })        
    })
);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)