Utilizing bcrypt in an axios request

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?

Answer №1

Did you experiment with utilizing method 1?

bcrypt.genSalt(saltRounds, function(err, salt) {
    bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
        // Save the hash in your password database.
    });
});

Afterwards, simply return the user.password?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can users change the displayed Twitch channel?

My coding skills aren't the greatest, especially when it comes to something like this. I've tried searching for a solution with no luck, so I apologize if this is too basic or impossible. I have a simple page that loads up Twitch with a predefin ...

Efficiently updating database records without the need for page reloads using EJS

I'm working on a project that resembles the comment section on Reddit. Users can leave comments and others can reply to those comments. My tech stack includes Node, Express, MySQL, and EJS. The issue I'm facing is implementing the upvote/downvo ...

Retrieve any webpage using AJAX

Hey there! I'm a beginner in AJAX and have a question that may seem basic to some. I understand that you can set up a page to respond to an AJAX call, but is it possible to request any page with AJAX? In other words, can all the functionalities of a ...

Issue with uncaught exceptions in promise rejection test

I am experiencing an issue with the following code: function foo(){ bar().catch(function(){ //do stuff } } function bar(){ return promiseReturner().then( function(result){ if(_.isEmpty(result)){ throw "Result is empty"; ...

Separate angular structure into various sections

I am developing a form builder using Angular dynamic form functionality. The form data is loaded from a JSON object, as shown below: jsonData: any = [ { "elementType": "textbox", "class": "col-12 col-md-4 col-sm-12", "key": "first_ ...

How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()? export class HistoricalPricesComponent implements OnInit, OnDestroy { private unsubscribe$ = new Subject < void > (); infoTitle ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

Exploring Objects using the for-in loop in ReactJS

This code is written in Reactjs. I am attempting to iterate through and print object data, but I keep encountering an error --> TypeError: Cannot read properties of undefined (reading 'state'). Could someone please help me identify what I am d ...

having trouble accessing a JavaScript array in AngularJS

Hey there, I'm currently working on a web application using AngularJS and I'm facing an issue with querying arrays. Check out the code snippet below: var angulararray = []; bindleaselistings.bindleaselistingsmethod().then(function(response) { ...

Troubleshooting Unpopulated Query Results in Objects when Using ExpressJS and Sequelize

I am facing an issue with populating my image object after executing a SQL query in a route. The query retrieves data from the database successfully, but I am unable to pass this data to my image object and use it in my view. It seems like I might be passi ...

Utilizing jQuery for AJAX to send data variables

Is it feasible to pass a variable to jQuery using the .ajax method? Instead of the traditional way, can I do something like this: <button onclick="sendQuery()"> function sendQuery(){ $.ajax({ type: "GET", url: "action.php", ...

Is it possible to populate an empty list of objects within the Page_Load scope after the page has finished loading?

I am facing a challenge where I need to populate the list var docfiles = new List<string>(); with file names uploaded by the user using dropzone js. However, the list remains empty because when the page loads for the first time, httpRequest.Files.C ...

What is the best way to organize Node/Express routes based on their type into different files?

My /router/index.js file is becoming too cluttered, and I want to organize my routes by group (user routes, post routes, gear routes) into separate files within /router/routes/. Here's what I currently have set up: app.js var express = require(&apos ...

Is it possible to create an online game using JavaScript?

Hey there, I'm interested in creating a simple online game that can be played in the browser. My main question is this: if I want two players to compete against each other online, can I achieve this by using HTML for the front-end and JavaScript for t ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

Utilizing a Node.js web server in conjunction with an Apache Cordova Application

I have created an innovative Apache Cordova Application that leverages a Node.js web server to retrieve data from a web API, enabling the JavaScript-based project to utilize the information obtained from the API. Is there a method to integrate this Node w ...

Changing the color variable of an object using an onClick function in JavaScript

I'm currently working on a simple game where users can draw using the keys W, A, S, and D. If you want to take a look at the progress I've made so far, here is a JSFiddle link. There's a collision function in the code that I no longer need, ...

Encountering a redirect error during the process of placing a call on hold to set

Here is my current process. When a call comes in, it gets placed into a queue. Once an agent is available, they initiate a connection by calling connect from the client-side Javascript application. The response acknowledges that an agent is attempting to ...

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

What is the best way to add a character within a YouTube JSON link?

Fetching json data from a link, the youtube format in the link is http:\/\/www.youtube.com\/watch?v=UVKsd8z6scw. However, I need to add the letter "v" in between this link to display it in an iframe. So, the modified link should appear as ht ...