【发布时间】: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