Internal server error on double registration, instead of Bad request on Brad Traversy MERN stack course

53 Views Asked by At

I have been having this problem for a week now. Anytime I try to register the same user twice, I get a error status (500) internal server error with the message "server error" on Postman but from the course, I am supposed to get an error status(400) Bad request with the msg: "User already exist" What could be the problem? Thanks

here is my code

const express = require('express');
const router = express.Router();
const User = require('../../models/User');
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');

// @route POST api/users
// @desc Register user
// @access Public
router.post(
  '/',
  [
    check('name', 'Name is required').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail(),
    check(
      'password',
      'Please enter a password with 8 or more characters'
    ).isLength({ min: 8 }),
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { name, email, password } = req.body;

    try {
      // See if user exist
      let user = await User.findOne({ email });

      if (user) {
        return res.status(400).json({ errors: [{ errors: errors.array() }] });
      }
      //  Get users gravatar

      const avatar = gravatar.url(email, {
        s: '200',
        r: 'pg',
        d: 'mm',
      });

      user = new User({
        name,
        email,
        avatar,
        password,
      });
      // Encrypt password

      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);

      await user.save();

      //  Return jsonwebtoken
      res.send('User registered great');
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server error');
    }
  }
);

module.exports = router;

I have gone through the code countless times, but still no reason why I'm getting the internal server error (500) instead of bad request (400). I even read it line by line, but still couldn't find the problem.

0

There are 0 best solutions below