简体   繁体   中英

Bcrypt didn't assign the hashed password to body.password variable

 module.exports.handle_sign_up = async (req,res) => { let body = req.body await bcrypt.hash(body.password, 10, (err,hash) => { body.password = hash console.log(hash) }) res.send(body) };

Above is my code which hashes body.password using bcrypt. I tried to assign the hashed password to body.password in callback function but when res.send(body) executed it instead returns unhashed password meanwhile when I tried to console.log(hash) the hashed password it succesfully log the hashed password to the console. Is there any problem that cause this?

module.exports.handle_sign_up = async (req,res) => {
    let body = req.body
    let hashedPassword;     
     try{
       hashedPassword = await bcrypt.hash(body.password,10);
       body.password = hashedPassword;
       console.log(hashedPassword,body.password);
     }catch(err){
       console.log(err)
    })

    res.send(body)
};


  • This is one way to do with try and catch
  • to do with callbacks
 module.exports.handle_sign_up = async (req,res) => {
    let body = req.body
         
     
      bcrypt.hash(body.password,10)
       .then((hashedPassword) => {
             body.password = hashedPassword;
          })
          .catch(err => console.log(err))
     

    res.send(body)
};
  • the mistake which you have done , is await returns a promise, if you dont store it , it is left as a promise which is not resolved
  • to resolve it , you need to store the promise, and then use then and catch

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