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

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

Barely populated React application following setup

I have been diving into React for quite some time now. However, today when I attempted to start a new project, it generated an almost empty project. My usual command create-react-app 'name-of-my-app' was used. It ran for a while and completed th ...

The local server for handling HTTP requests has ceased to operate

Recently, I set up the NPM package along with the http server within the "server" directory. Initially, everything was functioning smoothly; however, the server abruptly ceased operating. Upon attempting to launch the local http server, an error message a ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Using Node.js to retrieve a user's group memberships with NTLM authentication

I am currently utilizing express-ntlm for domain controller authentication, which is working smoothly. However, I now need to access the group details of the authenticated user, with authorization limited to a specific group. I have come across some examp ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

Error message: "No schema found for model 'User'.Create a schema using mongoose.model(name, schema)" with identifier 'MissingSchemaError'

I have been working on developing a schema for a user authentication system but keep encountering the error message mentioned above. I recently created two new pages with the code provided below: Users.js var mongoose = require ('mongoose'); va ...

Choosing JavaScript

<select> <script type="text/javascript"> $.get( 'http://www.ufilme.ro/api/load/maron_online/470', function(data){ var mydata = new Array(); var i = 0; // индекс масси ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

Using jQuery's .load() method is like including a file in a

Currently, Im working on revamping a company website that comes equipped with its very own CMS. Unfortunately, we are restricted from accessing the server configuration and FTP, which means I am limited to running only client-side files like HTML/CSS/J ...

Leverage Vue.js to utilize dropdown selected data

I need help with populating additional form elements based on the selection of a record from a dropdown menu that contains response data obtained through an axios request. <multiselect v-model="order.orderJCname" id="orderJCname" name="orderJCname" :op ...

"Cross-origin resource sharing problem while working with NodeJs, Express, and React on

Currently, I am working on a small project where I am using NodeJs and Express for the backend and React for the client side. In order to tackle CORS policy issues, I have implemented the "cors" npm package on the server side, but unfortunately, it doesn& ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

Creating a new file for a promise function

Initially, I managed to make this function work within a single file. However, I prefer organizing my code by splitting it into multiple files. // library.js file module.exports = { get: () =>{ return new Promise((reject, resolve) =>{ ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Is there a way to activate the autoplay feature for this?

I'm really new to Jquery and most of this code isn't mine, I'm just using it as a learning tool for creating sliders. If someone could give me some guidance on how to make this slider work automatically when the page loads, that would be gre ...

Using AJAX to add an event listener and passing parameters to a separate function

Short and sweet - I've got a loop that creates a series of dynamic buttons, and when one of them is clicked, I need to pass its id attribute to another file to generate a new page on the fly. Here's the code snippet: for (var i in data.contacts ...

When values are not passed to partial files in Express Handlebars, it can lead to difficulties in locating the error

I'm reaching out again because I didn't receive any response to my previous inquiry. I'm currently attempting to retrieve page names from the database to display in the sidebar, but I'm encountering difficulties. My sidebar is located i ...