javascript - NodeJS: HTTP GET returns the code instead of JSON object -


i have written following nodejs code retrieve json object 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 = "";     (property in obj) {     output += property + obj[property] ; } console.log(output);  }) 

however response i'm getting code(some sort of events.js code) can't understand (not html code). need figuring out i'm going wrong

including snippet reference ::

 // emit removelistener listeners on events  if (arguments.length === 0) {    (key in this._events) {      if (key === 'removelistener') continue;      this.removealllisteners(key);    }    this.removealllisteners('removelistener');    this._events = {};    return this;  } 

according api docs, http.get() passes serverresponse object callback. you're printing object (and parents') properties.

if want response body, should register listener on data event:

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

and re-assemble chunks.

response code can accessed via res.statuscode property , res.headers give response headers in array.


as requested, here's 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(); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -