Bcrypt 没有将哈希密码分配给 body.password 变量

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)
};

以上是我使用 bcrypt 散列 body.password 的代码。我试图在回调函数中将散列密码分配给 body.password 但是当 res.send(body) 执行它而不是 returns 未散列密码同时当我尝试 console.log(hash)哈希密码 它成功地将哈希密码记录到控制台。有什么问题导致这个吗?

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)
};


  • 这是处理 try and catch
  • 的一种方法
  • 与回调有关
 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)
};
  • 你犯的错误,是awaitreturns一个承诺,如果你不存储它,它就会作为一个未解决的承诺留下
  • 解决它,你需要存储承诺,然后使用then and catch