'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source