skip to Main Content

I am trying to get first name of a facebook user via their API.
This is my code

  var user = request("https://graph.facebook.com/v2.6/"+psid+"?fields=first_name,last_name&access_token="+token, function(err, res, body) {  
    console.log("name: " + body.first_name);
    console.log("body: " + body);
  });

This is the result:

name: undefined
body: {"first_name":"Anton","last_name":"Rosato"}

Why name is undefined ?

2

Answers


  1. It’s undefined because body is a string. Cast body = JSON.parse(body) before trying to read first_name.

    Login or Signup to reply.
  2. you can follow @yBrodsky advice or add options object into request with
    {json:true}. This will automatically add ‘Content-type: application/json’ into your request and parse response as json.

    reqeust.get(url, {json:true}, callbalck)
    

    https://www.npmjs.com/package/request#requestoptions-callback

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search