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

331
Views
Nodejs App crashing once wrong credentials are entered

Here is my Login Function

Once wrong credentials are entered it does send a response but then the app crashes

Im using Express ^4.17.2 and Nodejs v16.14.0 Versions

router.post(
  "/login",
  [
    body("email", "Enter a valid email").isEmail(),
    body("password", "Password cannot be blank").exists(),
  ],
  async (req, res) => {
    try {
    let success = true;
    // if there are errors , return Bad requests and the errors
    const errors = validationResult(req);
      try {
        if (!errors.isEmpty()) {
          success = false;
          return res.status(400).json({ error: errors.array()[0].msg });
        }

        const { email, password } = req.body;
        let user = await User.findOne({ email });

        if (!user) {
          success = false;
          return res
            .status(400)
            .json({ success, error: "Please use correct credentials" });
        }

        const passwordCompare = await bcrypt.compare(password, user.password);
        if (!passwordCompare) {
          success = false;
          return res
            .status(400)
            .json({ success, error: "Please use correct credentials" });
        }

        const data = {
          user: {
            id: user.id,
          },
        };

        const authToken = jwt.sign(data, JWT_SECRET);
        res.json({ success, authToken });
      } catch (error) {
        console.error(error.message);
        res.status(500).send("Internal Server Error");  // removing this also results in same error
      
      }
    } catch (error) {
      console.error(error);
    }
  }
);

Im using return statements so that should stop the program once there is a error but still im getting the error of Cannot set headers after they are sent to the client

Whats wrong with my code?

about 4 years ago · Juan Pablo Isaza
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!