简体   繁体   English

Passport.js 将错误发送回前端

[英]Passport.js sending error back to frontend

I have a problem to send back error message back to fronted while logging in with passport.js.在使用passport.js 登录时,我遇到了将错误消息发回前台的问题。

Here's my route:这是我的路线:

users.post('/login',
  passport.authenticate('local'),
  (req, res) => {
    res.sendStatus(201);
  },
);

And the strategy:和策略:

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
  },
  async (username, password, done) => {
    // let's assume we are checking here if there is a user in db

    if(user) {
      if(bcrypt.compareSync(password, user.password)) {
        return done(null, user);
      }
    } else {
        return done(null, false, { message: 'No user in db' });
    }
  }
));

This gives me 401 Anauthorized error in the browser.这在浏览器中给了我401 Anauthorized错误。 However I'd like to pass message ('No user in db') as well and maybe change status code.但是,我也想传递消息(“数据库中没有用户”),并且可能会更改状态代码。

Try this, the first parameter in the callback is the error parameter试试这个,回调中的第一个参数是错误参数

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password',
  },
  async (username, password, done) => {
    // let's assume we are checking here if there is a user in db

    if(user) {
      if(bcrypt.compareSync(password, user.password)) {
        return done(null, user);
      }
    } else {
        return done({ message: 'No user in db' }, false);
    }
  }
));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM