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
It’s undefined because body is a string. Cast
body = JSON.parse(body)
before trying to read first_name.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.https://www.npmjs.com/package/request#requestoptions-callback