简体   繁体   English

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

Above is my code which hashes body.password using bcrypt.以上是我使用 bcrypt 对 body.password 进行哈希处理的代码。 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.我试图在回调函数中将散列密码分配给 body.password,但是当 res.send(body) 执行时,它返回未散列的密码,同时当我尝试 console.log(hash) 散列密码时,它成功地将散列密码记录到安慰。 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这是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你做的错误是await返回一个承诺,如果你不存储它,它就会作为一个没有解决的承诺
  • to resolve it , you need to store the promise, and then use then and catch要解决它,您需要存储承诺,然后使用then and catch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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