0

I have written the following NodeJS code to retrieve the json object from a website

var http = require('http');
var url = {
  host: 'www.sample-website.com',
  headers: {
    "Accept": "application/json",
    'Content-Type': 'application/json'
  },
};
http.get(url, function(obj) {
  var output = "";
    for (property in obj) {
    output += property + obj[property] ;
}
console.log(output);

})

However as response I'm getting some code(some sort of events.js code) that I can't understand (not the HTML code). Need help figuring out where I'm going wrong

Including a snippet for reference ::

 // emit removeListener for all listeners on all events
 if (arguments.length === 0) {
   for (key in this._events) {
     if (key === 'removeListener') continue;
     this.removeAllListeners(key);
   }
   this.removeAllListeners('removeListener');
   this._events = {};
   return this;
 }
1
  • Just a friendly suggestion, Please use a framework like express or connect Commented Jun 1, 2015 at 5:11

1 Answer 1

2

According to API docs, http.get() passes a ServerResponse object to its callback. You're currently printing that object (and its parents') properties.

If you want to get the response body, you should register a listener on its data event:

res.on('data', function (chunk) {
  console.log('BODY: ' + chunk);
});

and re-assemble the chunks.

Response code can be accessed via res.statuscode property and res.headers will give you the response headers in an array.


As requested, here's a full sample code:

var http = require('http');
var url = 'http://stackoverflow.com';
// ...
http.request(url, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    console.log('BODY: ');
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        process.stdout.write(chunk);
    });
}).end();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.