【问题标题】:how to send error message to client?如何向客户端发送错误消息?
【发布时间】:2019-01-26 10:08:04
【问题描述】:

我正在使用带有本地策略的护照。但是当credential 不匹配或(user is not exit is DB)时,我想发送消息和状态

这里是代码

router.js

const passport = require('passport');
const passportConfig = require('../passport')
const passportSignIn = passport.authenticate('local', { session: false });

router.route('/login',)
    .post(passportSignIn,controller.login)

关于控制器文件

 login: async (req, res, next) => {
        console.log(req.body);
        res.json({status:200})

    }

passport.js

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done) => {

    const user = await db.User.findOne({where: {email: email}});
    if (!user) {
        return done(null, false,{message:"No user exit"});
    }
    const isMatch = await bcrypt.compare(password, user.dataValues.password);
    console.log(isMatch, 'isMatch');
    if (!isMatch) {
        return done(null, false);
    }

    // Otherwise, return the user
    done(null, user);

}))

客户端代码

当用户单击login 按钮时,它会首先转到/login 路径,然后转到passportSignIn 函数或以下函数。

 `new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done) => {`

现在,如果找不到用户,我想在客户端上发送此消息作为响应(“无用户退出”)

return done(null, false,{message:"No user exit"});

【问题讨论】:

    标签: javascript jquery node.js sequelize.js passport.js


    【解决方案1】:

    你必须更新你的登录控制器,像这样:

    login: (req, res, next) => {
            console.log(req.body);
            passport.authenticate('yourStrategy', function(err, user, info) {
                if (err) {
                  return res.status(500).json("Internal Server Error");
                }
                if (!user) {
                  // This 'info' variable below would be - { message: "No user exit" }
                  // as you passed in the done() callback as the third param
                  return res.status(404).json(info.message);
                }
            }
          }
    

    【讨论】:

    • 我可以在这里使用 asyn await
    • 当然可以!自己尝试,让我知道它是否有效/无效。 :)
    • 您的功能运行良好,请告诉我如何使用异步等待来实现这一目标
    • 为什么要使用异步?有什么具体原因吗? ://
    • 我的控制器已经是异步的,所以我将在这里使用等待而不是回调
    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2015-04-17
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 2015-04-07
    • 2019-04-29
    相关资源
    最近更新 更多