Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is body in a nodejs http.get response?

Tags:

http

node.js

I'm reading the docs at http://nodejs.org/docs/v0.4.0/api/http.html#http.request, but for some reason, I can't seem to to actually find the body/data attribute on the returned, finished response object.

> var res = http.get({host:'www.somesite.com', path:'/'})  > res.finished true  > res._hasBody true 

It's finished (http.get does that for you), so it should have some kind of content. But there's no body, no data, and I can't read from it. Where is the body hiding?

like image 286
mikemaccana Avatar asked Aug 06 '11 17:08

mikemaccana


People also ask

What is HTTP response body?

An HTTP response is made by a server to a client. The aim of the response is to provide the client with the resource it requested, or inform the client that the action it requested has been carried out; or else to inform the client that an error occurred in processing its request.


2 Answers

http.request docs contains example how to receive body of the response through handling data event:

var options = {   host: 'www.google.com',   port: 80,   path: '/upload',   method: 'POST' };  var req = http.request(options, function(res) {   console.log('STATUS: ' + res.statusCode);   console.log('HEADERS: ' + JSON.stringify(res.headers));   res.setEncoding('utf8');   res.on('data', function (chunk) {     console.log('BODY: ' + chunk);   }); });  req.on('error', function(e) {   console.log('problem with request: ' + e.message); });  // write data to request body req.write('data\n'); req.write('data\n'); req.end(); 

http.get does the same thing as http.request except it calls req.end() automatically.

var options = {   host: 'www.google.com',   port: 80,   path: '/index.html' };  http.get(options, function(res) {   console.log("Got response: " + res.statusCode);    res.on("data", function(chunk) {     console.log("BODY: " + chunk);   }); }).on('error', function(e) {   console.log("Got error: " + e.message); }); 
like image 58
yojimbo87 Avatar answered Sep 18 '22 15:09

yojimbo87


I also want to add that the http.ClientResponse returned by http.get() has an end event, so here is another way that I receive the body response:

var options = {   host: 'www.google.com',   port: 80,   path: '/index.html' };  http.get(options, function(res) {   var body = '';   res.on('data', function(chunk) {     body += chunk;   });   res.on('end', function() {     console.log(body);   }); }).on('error', function(e) {   console.log("Got error: " + e.message); });  
like image 41
bizi Avatar answered Sep 20 '22 15:09

bizi