'Failed to load resource: the server responded with a status of 500 (Internal Server Error), Error: Request failed with status code 500

I'm working on this social media app. and every time I try to sign up/sign in to the application it gives me this error.

Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Register.jsx:27 Error: Request failed with status code 500
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:54:1)

Here the server-side code

const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");

//REGISTER
router.post("/register", async (req, res) => {
  try {
    //generate new password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

    //create new user
    const newUser = new User({
      username: req.body.username,
      email: req.body.email,
      password: hashedPassword,
    });

    //save user and respond
    const user = await newUser.save();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json(err)
  }
});

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    !user && res.status(404).json("user not found");

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    !validPassword && res.status(400).json("wrong password")

    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

module.exports = router;

Tech-Stack used in API: MongoDB, Node.js, and Express



Solution 1:[1]

When you serve the 500 error page, it is highly recommended to log the error in the output (not in the response, but in the logs):

Also, you have to return when sending the response, so that you do not write the head multiple times.

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) { 
      return res.status(404).json("user not found");
    }
    const validPassword = await bcrypt.compare(req.body.password, user.password)

    if (!validPassword) {
      return res.status(400).json("wrong password")
    }

    res.status(200).json(user)
  } catch (err) {
    console.error(err)
    res.status(500).json(err)
  }
});

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Ionică Bizău