Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda