9

I'm having trouble extracting the response body of a POST request in Node.js.I'm expecting the RESPONSE: 'access_token=...'

Should be pretty simple, not sure what I should be doing though. (Node v0.4.3)

Here's my code snippet.

payload = 'client_id='+client_id + '&client_secret='+ client_secret
                                  + '&code='+ code
   var options = {
      host: 'github.com',
      path: '/login/oauth/access_token?',
      method: 'POST'
   };

   var access_req = https.request(options, function(response){
      response.on('error', function(err){
         console.log("Error: " + err);
      });
      // response.body is undefined
      console.log(response.statusCode);
   });

   access_req.write(payload);
   access_req.end();
   console.log("Sent the payload " + payload + "\n");
   res.send("(Hopefully) Posted access exchange to github");
Kiran Ryali
  • 1,371
  • 3
  • 12
  • 18

2 Answers2

9

You'll need to bind to response's data event listener. Something like this:

var access_req = https.request(options, function(response){
   response.on('data', function(chunk) {
       console.log("Body chunk: " + chunk);
   });
});
Miikka
  • 4,573
  • 34
  • 47
  • 3
    Notice that data can come in several chunks so, if I'm not wrong, you must listen for the 'end' event to be sure that you have the whole response body. – Guido Jan 13 '13 at 20:02
  • 1
    Along the lines of what @GuidoGarcía said here's a pointer to a more comprehensive answer that shows how to get the entire body. http://stackoverflow.com/questions/5083914/get-the-whole-response-body-when-the-response-is-chunked – WolfgangCodes May 23 '13 at 21:40
7

As Miikka says, the only way to get the body of a response in Node.js is to bind an event and wait for each chunk of the body to arrive. There is no response.body property. The http/https modules are very low-level; for nearly all applications, it makes more sense to use a higher-level wrapper library.

In your case, mikeal's request library is perfectly suited to the task. It waits until the full body of the response has arrived, then calls your callback of the form (err, response, body).

For parsing request bodies, you would probably want to use Connect with the bodyParser middleware (or the popular Express, which further extends Connect).

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196