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

175
Vistas
Express app error: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
const router = require("express").Router();
const mongoose = require("mongoose");
const User = require("../models/Users");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

// Route 1: create new user at /api/createuser
router.post("/createuser", async (req, res) => {
  try {
    console.log(req.body);
    const salt = await bcrypt.genSaltSync(10);
    const hash = await bcrypt.hashSync(req.body.password, salt);
    password = hash;
    const user = new User({
      name: req.body.name,
      email: req.body.email,
      password: password,
    });
    user
      .save()
      .then(() => {
        res.json({ message: "User created successfully" });
      })
      .catch((err) => {
        res.json({ message: "Error: " + err });
      });
    console.log(password);
  } catch (err) {
    res.json({ message: err });
  }
});

// Route 2: Login user at /api/login
router.post("/login", async (req, res) => {
  try {
    console.log("login endpoint triggered");
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
      res.json({ message: "User does not exist" });
    }
    const passwordIsValid = await bcrypt.compare(
      req.body.password,
      user.password
    );
    if (!passwordIsValid) {
      res.json({ message: "Invalid password" });
    } else {
      const data = {
        id: user._id,
      };
      const token = await jwt.sign(data, process.env.SECRET);
      res.json(token);
    }
  } catch (error) {
    res.json({ message: error });
  }
});

module.exports = router;

Whenever I am testing the login endpoint, my app crashes if i try to put incorrect password or unregistered email. It says Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client I have only sent one response to the client even then it is showing this error. In the terminal, it is showing error at catch block of login endpoint. Can anyone look into it and tell me why am i getting this error.

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

0

Make sure that when the response is an error, the rest of the middleware is not executed any more. For example, put a return before the res.json statement:

if (!user) {
  return res.json({ message: "User does not exist" });
}

Otherwise, the "Invalid password" json might get issued after this one, but two res.jsons in one response lead to the observed error.

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