Calling a JSON API with Node.js

Viewed 183557

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)
6 Answers

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;
Related