Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda