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?
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.
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); });
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); });
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