I am trying to get the facebook profile picture of the user logged into my application. Facebook's API states that http://graph.facebook.com/517267866/?fields=picture
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://graph.facebook.com/517267866/?fields=picture';
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:
undefined:1
^
SyntaxError: Unexpected token o
at Object.parse (native)
I think that for simple HTTP requests like this it's better to use the
request
module. You need to install it with npm (npm install request
) and then your code can look like this:Unirest library simplifies this a lot. If you want to use it, you have to install
unirest
npm package. Then your code could look like this:Problems with other answers:
JSON.parse
All of the answers here use
JSON.parse()
in an unsafe way. You should always put all calls toJSON.parse()
in atry/catch
block especially when you parse JSON coming from an external source, like you do here.You can use
request
to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer usingrequest
module but it usesJSON.parse()
to manually parse JSON - which should always be run inside atry {} catch {}
block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.Other answers that use
http
also useJSON.parse()
without checking for exceptions that can happen and crash your application.Below I'll show few ways to handle it safely.
All examples use a public GitHub API so everyone can try that code safely.
Example with
request
Here's a working example with
request
that automatically parses JSON:Example with
http
andtry/catch
This uses
https
- just changehttps
tohttp
if you want HTTP connections:Example with
http
andtryjson
This example is similar to the above but uses the
tryjson
module. (Disclaimer: I am the author of that module.)Summary
The example that uses
request
is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.The
res
argument in thehttp.get()
callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:I'm using get-json very simple to use:
Import
get-json
To do a
GET
request you would do something like: