Javascript对象是未定义的,即使它明显存在

时间:2018-12-23 19:16:10

标签: node.js get request facebook-messenger

我使用get请求(使用请求npm)来访问我的机器人的Facebook个人资料信息,它显然得到了一个正文,但是当我尝试访问正文中的名字时,它接着说它是未定义的。

代码如下:

      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);

期望的输出是身体,然后是杰克,杰克,但Heroku的输出如下所示:

2018-12-23T19:06:47.739490 + 00:00 app [web.1]:正文:{“ 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]:未定义

2018-12-23T19:06:47.739603 + 00:00 app [web.1]:未定义

1 个答案:

答案 0 :(得分:0)

问题在于,facebook提供了一个JSON字符串,但是我的代码试图像luschn所指出的那样,像访问Javascript对象一样访问它。

此问题的解决方法是使用JSON.parse(body)修改代码,然后将JSON字符串转换为Javascript对象,可以通过我最初尝试的方法进行访问。

相关问题