简体   繁体   中英

Unhandled promise rejection error value is not defined in Node.js

We are trying to fix this create user controller in Node.js Express. The problem is that when you click sign up in the front end it throws this error: Unhandled promise rejection error value is not defined. Shows on line 28 but looks that's not the main issue. Here is the code:

async CreateUser(req, res) {
    const userEmail = await User.findOne({
      email: req.body.email
    });
    if (userEmail) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Email already exist' });
    }

    const userName = await User.findOne({
      username: req.body.username
    });
    if (userName) {
      return res
        .status(HttpStatus.CONFLICT)
        .json({ message: 'Username already exist' });
    }

    return bcrypt.hash(value.password, 10, (err, hash) => {
      if (err) {
        return res
          .status(HttpStatus.BAD_REQUEST)
          .json({ message: 'Error hashing password' });
      }
      const body = {
        username: value.username,
        email: value.email,
        password: hash
      };
      User.create(body)
        .then(user => {
          res
            .status(HttpStatus.CREATED)
            .json({ message: 'User created successfully', user, token });
        })
        .catch(() => {
          res
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .json({ message: 'Error occured' });
        });
    });
  },

How can this be solved?

error : Unhandled promise rejection error value is not defined .

in your code see : where is value ? , it should be req.body.password

return bcrypt.hash(value.password, 10, (err, hash) => {
      if (err) {
        return res
          .status(HttpStatus.BAD_REQUEST)
          .json({ message: 'Error hashing password' });
      }
      const body = {
        username: value.username,
        email: value.email,
        password: hash
      };

code to update :

return bcrypt.hash(req.body.password, 10, (err, hash) => {
          if (err) {
            return res
              .status(HttpStatus.BAD_REQUEST)
              .json({ message: 'Error hashing password' });
          }
          const body = {
            username: req.body.username,
            email: req.body.email,
            password: hash
          };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM