简体   繁体   中英

How to handle 401 error status code error in Node.js/Express?

I am working on login functionality in my project, now, flow looks like this (from front-end to back-end):

async login() {
  await login({
    password: this.userPassword,
    login: this.userLogin,
    twoFactor: this.twoFactor
  }).then((res) => {
    if (res.error) {
      //
    } else {
      console.log(res)
    }
  })
}

And here is starts problems, as you can see if something goes wrong, I return status code 401 and some error message. When I login with correct data, there is no problem with getting token, but when I provide wrong data I have external pending login endpoint in development tools in browser and then, after some time, Error: Request failed with status code 401 in front end terminal. Without this status(401) with just JSON it works fine, but when I try to add 401 code, application crashes.

const userService = require('./../services/userService')
const crypto = require('./../services/cryptoService')
const jwt = require('./../services/jwtService')
const twoFactorService = require('node-2fa')

module.exports = {
  login: async (req, res) => {
    let { login, password, twoFactor } = req.body

    password = crypto.encrypt(password, process.env.APP_KEY)
    const result = await userService.getUserToLogin(login, password)

    if (!result) {
      res.status(401).json({
        error: 'Unauthorized'
      })
    } else {
      const faCode = result.twofatoken
      const result2F = twoFactorService.verifyToken(faCode, twoFactor);
      if ( !result2F || result2F.delta !== 0 ) {
        res.status(401).json({
          error: 'Unauthorized'
        })
      } else {
        const userId = crypto.encrypt(result.id, process.env.CRYPTO_KEY)
        const token = await jwt.sign({
          uxd: userId,
        });
        res.json(token);
      }
    }
  }
}

Actually, I have no idea on what to do with that and how to handle this error.

Ok, here is the answer. Actually, you just need to handle this error in your router:

router.post('/login', async (req, res) => {
  try {
    const data = await api.post('/login', req.body)
    res.json(data.data)
  } catch (e) {
    // Probably you have here just console.log(e), but this way, you can handle it
    res.status(e.response.status).json(e.response.data)
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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