0

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?

vvspower
  • 49
  • 1
  • 6
  • The error is saying that the headers for the response have been sent. This can of course happen if you got to the point of sending something, and then there is an error. You then are doing a `res.status(500)`, Due to unhandled Promises now terminating Node, you will need to handle this. One way of doing this is wrap everything in another `try catch`, but just `console.error`, don't do anything with `res`.. – Keith Mar 29 '22 at 12:18
  • @Keith Tried it. Still the same error :( – vvspower Mar 29 '22 at 12:32
  • And your node process still terminates?, could you update the snippet above with what you tried.. – Keith Mar 29 '22 at 12:33
  • @Keith i have updated it – vvspower Mar 29 '22 at 12:41
  • Put the `try` as the first line, your still calling `validationResult`, The only other thing I can think is that not all Javascript errors are instances of Error,.. so on the outer catch, just do `console.error(error)`.. In theory in JS you can throw anything, eg. `throw 2`, – Keith Mar 29 '22 at 12:59
  • @Keith ive done what you have said and updated the snippet. i dont quite understand with what you meant by "your still calling validationResult". the code still gives me error. could you help me out with that – vvspower Mar 29 '22 at 18:02
  • I meant you was calling validationReult outside the try. Seen as you have put a `try catch`, there should be nothing here making your process terminate. Yes, you should still get the error, but node process should still be running, are you saying it's still terminating.. If so, not sure what else.. – Keith Mar 29 '22 at 18:05

1 Answers1

1

I had a similar issue and found this discussion addressing this error instance. However, in my case, it was a simple issue of the code, breaking after the wrong credentials had been caught. The error was in the lines of code coming after the if-condition block supposed to catch wrong credentials. You might be using a package(eg "jwt") not properly imported, or passing in the wrong arguments.