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");
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);
});
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With