【问题标题】:How to get data from an weather api and access it's data如何从天气 api 获取数据并访问它的数据
【发布时间】:2020-06-30 23:37:08
【问题描述】:

我试图从这个程序中获取天气 API 数据,我的问题是这个程序的输出是未定义的,我期望一个对象,为什么输出是未定义的以及如何获得所需的对象?


const url = "https://api.weatherapi.com/v1/current.json?key=KEYREDACTED&q=London"
const url1 = "https://api.openweathermap.org/data/2.5/weather?q=New Delhi,India&appid=KEYREDACTED"

const apiRequest = https.get(url,(res) => {
  let data ="";
  res.on("data",(chunk) => {
      data+=chunk;
      JSON.parse(data);
  })
  res.on("end",() => {
      console.log(data.location);
  });
});

【问题讨论】:

  • 不是 node.js 方面的专家,但您不应该先检索所有数据然后才解析 JSON 吗?您提供的链接返回正确的数据。

标签: javascript node.js api http backend


【解决方案1】:

重要提示:切勿在您的问题中包含 API 密钥/ID(?key=&appid= 之后的部分)。其他人可以使用它们并耗尽您的流量。

您正在使用JSON.parse 解析数据,而仍在接收响应。将其移至 "end" 部分。

https.get(url,(res) => {
  let data ="";
  res.on("data",(chunk) => {
      // Data is being received in chunks, we add it to the data variable to save it
      data+=chunk;
  })
  res.on("end",() => {
    // all data has been received, now we can parse it and are done
    const parsedData = JSON.parse(data);
    console.log(parsedData);
  });
});

parsedData 可能就是您要查找的对象。

【讨论】:

    【解决方案2】:

    我只想在 ffritz 响应中添加正确的内容,并说有一些 npm 包可以将你的工作减半,或者只使用纯 ES6 和 fetch,这也非常简单,可以让所有转换为你工作.

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(data => console.log(data));

    这里有一些文档。

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 2022-12-18
      • 2020-11-25
      • 2021-03-08
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2012-11-01
      相关资源
      最近更新 更多