簡體   English   中英

如何在axios調用中調用bcrypt

[英]How to call bcrypt inside axios call

我正在對某個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,它將顯示原始密碼,並且沒有加密,並保存到數據庫中。

知道我在這里想念什么嗎? 如何固定我的功能來完成我想做的事情?

您是否嘗試過使用技術1?

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

然后只需返回user.password?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM