Lukas Gund
Lukas Gund

Reputation: 711

Express async post request

My Code

My code in the backend will get the post data and call a async function

app.post('/login', async (req, res) => {
   var mail = decodeURIComponent(req.body.mail), password;
   await bcrypt.hash(decodeURIComponent(req.body.password), saltRounds, function(err, hash) {
       ...
   });
});

Problem

If I want to start the application I get this warning:

[DEP0013] DeprecationWarning: Calling an asynchronous function without callback is depre

is there a better solution?

EDIT

I got the same warning if I just do this, but I am not sure how can I make a callback here.

app.post('/login', async (req, res) => { res.json({ success: true }); });

Upvotes: 1

Views: 6005

Answers (1)

Tomalak
Tomalak

Reputation: 338406

bcrypt (this one, right?) is not a promisified library.

You cannot await its functions.

app.post('/login', (req, res) => {
  bcrypt.hash(req.body.password, saltRounds, (err, result) => {
    if (err) {
      // error
      return;
    }
    // success
  });
});

But you can promisify it if you want.

const util = require('util');
const bcrypt = require('bcrypt');
const hashAsync = util.promisify(bcrypt.hash);

app.post('/login', (req, res) => {
  hashAsync(req.body.password, saltRounds).then(result => {
    // success
  }).catch(err => {
    // error
  });
});

Of course the above can be written as async/await, too. Don't forget the try/catch, though.

Also, I am sure that you do not have to do any URL-decoding. All the values in req.body are already decoded. Calling decodeURIComponent() yourself means you will end up decoding the values twice. This will cause errors as soon as the value actually contains something like %xx somewhere - especially in passwords this will occur sooner or later.

Upvotes: 2

Related Questions