【问题标题】:Javascript object is undefined, even though it is clearly thereJavascript 对象未定义,即使它显然存在
【发布时间】:2018-12-23 19:16:10
【问题描述】:

我使用获取请求(使用请求 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);

预期的输出是正文,然后是 Jake,Jake,但 Heroku 的输出如下所示:

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 应用[web.1]:未定义

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

【问题讨论】:

  • 你确定它是一个对象而不是一个字符串?
  • 请求范围在哪里关闭?你能修复你的代码示例吗?
  • @luschn 非常感谢你,脑筋急转弯。它是一个 JSON 对象,得到它

标签: node.js get request facebook-messenger


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2012-04-17
    • 2023-02-10
    • 2020-06-06
    相关资源
    最近更新 更多