Sven Sven - 5 months ago 20x
JSON Question

Calling a JSON API with Node.js

I am trying to get the facebook profile picture of the user logged into my application. Facebook's API states that
returns the correct URL as a JSON object.

I want to get the URL to the picture out of my code. I tried the following but I am missing something here.

var url = '';

http.get(url, function(res) {
var fbResponse = JSON.parse(res)
console.log("Got response: " + fbResponse.picture);
}).on('error', function(e) {
console.log("Got error: " + e.message);

Running this code results in the following:


SyntaxError: Unexpected token o
at Object.parse (native)


The res argument in the http.get() callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:

var url = '';

http.get(url, function(res){
    var body = '';

    res.on('data', function(chunk){
        body += chunk;

    res.on('end', function(){
        var fbResponse = JSON.parse(body);
        console.log("Got a response: ", fbResponse.picture);
}).on('error', function(e){
      console.log("Got an error: ", e);