Reputation: 305
I use a get request (using request npm) to access facebook profile info for my bot, and it clearly gets a body but when I try to access first name in the body, it then says that it is undefined.
The code is as such:
request(`https://graph.facebook.com/${sender_psid}?fields=first_name,last_name,profile_pic&access_token=${PAGE_ACCESS_TOKEN}`, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body);
console.log(body["first_name"]);
console.log(body.first_name);
The expected output is the body and then Jake, Jake but the output from Heroku can be seen below:
2018-12-23T19:06:47.739490+00:00 app[web.1]: body: {"first_name":"Jake","last_name":"Walker","profile_pic":"https://platform-lookaside.fbsbx.com/platform/profilepic/?psid=XXXXXXX","id":"XXXXXXXXX"}
2018-12-23T19:06:47.739542+00:00 app[web.1]: undefined
2018-12-23T19:06:47.739603+00:00 app[web.1]: undefined
Upvotes: 1
Views: 57
Reputation: 305
The problem was that facebook was providing a JSON string, but my code was trying to access it as if it was a Javascript object as pointed out by luschn.
The fix to this is adapting the code to using JSON.parse(body) which then converts the JSON string to a Javascript object, which can be accessed through the method I was originally trying.
Upvotes: 2