【问题标题】:How to get property from API Response in Node JS?如何从 Node JS 中的 API 响应中获取属性?
【发布时间】:2022-02-04 02:38:07
【问题描述】:

我在节点 JS 中有一个 API,它调用另一个 API - openWeatherMap。 这是我调用天气 API 时的邮递员响应:

但是这个响应带来了 API 中的每个参数,我想向用户展示例如 temp.min。我该怎么做?

【问题讨论】:

  • 请分享调用其他api后发送该有效负载的nodejs代码部分
  • request({ url: url, json: true }, function (error, response) { if (error) { console.log('Unable to connect to Forecast API'); } else { res .status(200).send(response.body.list[0].main.temp_min); } })
  • 在发送之前做一个控制台日志,看看数据是否存在

标签: javascript node.js json api openweathermap


【解决方案1】:

您可以使用它们的键访问 json 对象值,例如:

response.body.list[0].main.temp_min

【讨论】:

  • 这不起作用。它发送一条错误消息:Cannot read properties of undefined (reading '0')
【解决方案2】:

您应该使用“点符号”来访问所需的对象属性。 Refer to the MDN Docs 或 W3 之类的资源,了解有关如何使用它的更多信息。

在您的情况下,您可以声明一个等于您希望访问的属性的变量:

minTemp = response.body.list[0].main.temp_min

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 2018-05-21
    • 2022-01-26
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多