0

I was learning JWT by following a YouTube tutorial. When i started hashing the password it threw me this error. I printed the salt it's printing fine but there's some issue while hashing.

I tried for try catch method too but it automatically went to the catch part.

The error is as follows:

https://i.stack.imgur.com/KJVPk.png

const User = require('../models/User');
const {registerValidation} = require('./validation');
const bcrypt = require('bcryptjs');

router.post("/register", async (req, res) => {
    //VALIDATE BEOFRE ADDING USER
    const {error} = registerValidation(req.body);
    if(error) return res.status(400).send(error.details[0].message);

    //Checking user is already in the database
    const emailExist = await User.findOne({email: req.body.email});
    if(emailExist) return res.status(400).send("Email already exists");

    const salt = await bcrypt.genSalt(10);
    const hashPassword = await bcrypt.hash(req.body.passowrd, salt);
    
    //Create a new user
    const user = new User({
        name: req.body.name,
        email: req.body.email,
        password: hashPassword
    });
    try {
        const savedUser = await user.save();
        res.send(savedUser);
    } catch(err) {
        console.log(err);
        res.status(400).send(err);
    }
});

module.exports = router; 

1 Answers1

0

Me funciono así amigo.

router.post('/', async (req, res) => {
  let user = new User({
    name: req.body.name,
    email: req.body.email,
    passwordHash: bcrypt.hashSync(req.body.passwordHash, 10),
    phone: req.body.phone,
    isAdmin: req.body.isAdmin,
    street: req.body.street,
    apartment: req.body.apartment,
    zip: req.body.zip,
    city: req.body.city,
    country: req.body.country,
  })
  user = await user.save()

  if (!user) return res.status(400).send('the user cannot be created!')

  res.send(user)
})