Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!