0

I am writing a server in node using async/await (http://stackabuse.com/node-js-async-await-in-es7/ and using bable to transpile) and request (https://github.com/request/request). I am trying to make a post request to an external api and access the http response headers. I can only figure out how to access the request that I am sending. How do I get the HttpResponse?

Here is the code

var options = {
  url: externalUrl,
  form: body
};

try {
  var httpResponse = await request.post(options);
  console.log(httpResponse.headers.location);
  return "post request succeeded!";
} catch (err) {
  return done(err, null);
}
Trent Punt
  • 1
  • 1
  • 1
  • `done(err, null)`? You should not use callbacks any more when you are working with promises and async/await. – Bergi Sep 21 '16 at 00:19

2 Answers2

1

Looks like request is implemented with callbacks. ES7 async/await only works with Promises. You can use a library like bluebird to promisify all methods from request. Async/await should work afterwards.

Dan
  • 506
  • 5
  • 18
0

If you are using Request you don't need async.

You can easy do this:

request({
    headers: {
        'Content-Type': 'application/json',
    },
    uri: url,
    body: JSON.stringify(options),
    method: 'POST'
}, function (err, res, body) {
    var obj = JSON.parse(body);
    if(err){
       console.log("Ooops: " + err);
    }else{
       console.log(res.headers['content-type']);
       //Do some stuff with the server response;
    }
}); 
manuerumx
  • 1,230
  • 14
  • 28