Currently, I am working on an axios call to a specific json file. My goal is to obtain input from a front-end framework and then pass that data to my server using express.
The task at hand involves encrypting the password retrieved from request.body.password
before storing it in the database. However, the default documentation for bcrypt utilizes asynchronous calls with callbacks. Despite attempting to log the result before and after encryption, it seems that bcrypt functions only within itself, failing to encrypt the password prior to saving it to the database.
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('The user's password is... >>>>>>>>>', req.body.password) // displays the 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 hashed password >>>>>>>>>', user.password)
// The expectation was to display the encrypted password, however, it appears to not encrypt outside the callback
// save data to user
user.save(err => {
if (err) {
console.log('issue adding user', err);
} else {
res.status(200).send();
}
});
})
.catch(err => {
console.log('error on user', err);
res.status(500).send();
});
});
Upon logging this, I discovered that the original plain text password gets displayed instead of its encrypted version when saved in the database.
Is there something crucial that I might be overlooking? What adjustments can I make to ensure that my function performs as intended?