简体   繁体   English

如何从天气 api 获取数据并访问它的数据

[英]How to get data from an weather api and access it's data

I tried to get weather API data from this program,my problem is that this program's output is undefined,I expected an object,Why the output is undefined and how I can get the required object? I tried to get weather API data from this program,my problem is that this program's output is undefined,I expected an object,Why the output is undefined and how I can get the required object?


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

Important: Never include API Keys/IDs in your question (the part after ?key= and &appid= ).重要提示:切勿在您的问题中包含 API 密钥/ID(在?key=&appid=之后的部分)。 Other people can use them and use up your traffic.其他人可以使用它们并耗尽您的流量。

You are parsing data using JSON.parse while the response is still being received.您正在使用JSON.parse解析数据,同时仍在接收响应。 Move that to the "end" part.将其移至"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);
  });
});

The parsedData is probably the object you are looking for. parsedData可能是您正在寻找的 object。

I just would like to add to the ffritz response which is correct and say that there are npm packages that will cut your work in half or just use pure ES6 and fetch which is also super simple and makes all that conversion work for you.我只是想补充一下正确的 ffritz 响应,并说有 npm 包可以将你的工作减半,或者只使用纯 ES6 和 fetch,这也非常简单,可以让所有转换为你工作。

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

Here is some documentation.这是一些文档。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM