【问题标题】:Bcrypt didn't assign the hashed password to body.password variableBcrypt 没有将散列密码分配给 body.password 变量
【发布时间】:2021-02-27 09:23:13
【问题描述】:

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) 执行时它返回未散列的密码,同时当我尝试 console.log(hash) 散列密码时,它成功地将散列密码记录到安慰。有什么问题导致这个吗?

【问题讨论】:

  • 大多数async and await 的初学者都会犯同样的错误,你需要存储promise来解决或拒绝它。

标签: node.js express bcrypt


【解决方案1】:
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)
};
  • 你犯的错误是await返回一个promise,如果你不存储它,它就作为一个没有解决的promise留下
  • 要解决它,你需要存储promise,然后使用then and catch

【讨论】:

  • 这解决了我的问题,非常感谢您提供有用的解释!
猜你喜欢
  • 1970-01-01
  • 2016-03-23
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 2021-06-04
  • 2019-07-17
相关资源
最近更新 更多