【问题标题】:How to call bcrypt inside axios call如何在 axios 调用中调用 bcrypt
【发布时间】:2018-04-23 10:17:45
【问题描述】:

我正在对某个 json 文件进行 axios 调用。基本上我正在尝试从前端框架获取输入并通过 express 将数据传递到我的服务器。

所以我在这里尝试做的是,我想先加密从request.body.password 获得的密码,然后再将其保存到数据库中。

bcrypt 的默认文档是使用回调的异步调用,所以我所做的是在加密之前和之后控制台记录结果,但似乎 bycrypt 仅在其内部工作,并且在将密码保存到之前不会加密密码数据库。

router.post('/call/user', (req, res) => {
  var user = new User(req.body);
    axios
        .get(
          `http://localhost:3000/mydata/data.json`
        )
        .then(response => {
          user.lat = response.data.results[0].geometry.location.lat;
          user.lng = response.data.results[0].geometry.location.lng;

          console.log('here is the user password... >>>>>>>>>', req.body.password) // returns original text password

            bcrypt.hash(req.body.password, 10, function(err, hash){
              if(err){
                console.log(err);
              }
              user.password = hash;
            });

            console.log('this is the hash password >>>>>>>>>', user.password)
// i expect this to return the encrypted password but it seems it doesn't encrypt it outside the callback


         // saving data to user
          user.save(err => {
            if (err) {
              console.log('problem adding user', err);
            } else {
              res.status(200).send();
            }
          });
        })
        .catch(err => {
          console.log('err on user', err);
          res.status(500).send();
        });
});

最后,如果我 console.log 它将显示原始文本密码而不对其进行加密保存到数据库。

知道我在这里缺少什么吗?如何修复我的功能来做我想做的事情?

【问题讨论】:

    标签: javascript express axios bcrypt


    【解决方案1】:

    你尝试过使用技巧 1 吗?

    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
            // Store hash in your password DB.
        });
    });
    

    然后只返回user.password?

    【讨论】:

    • 我相信我的功能可以工作,但只是我需要找到一种方法来使用输出加密密码,然后再将其保存到数据库。
    猜你喜欢
    • 2021-02-21
    • 2020-06-05
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多