Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Getting the response body from a POST request

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");
like image 787
Kiran Ryali Avatar asked Mar 20 '11 06:03

Kiran Ryali


2 Answers

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);
   });
});
like image 113
Miikka Avatar answered Oct 26 '22 17:10

Miikka


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).

like image 25
Trevor Burnham Avatar answered Oct 26 '22 18:10

Trevor Burnham