简体   繁体   English

OpenWeatherMap API 返回“未定义”

[英]OpenWeatherMap API returning 'undefined'

My previous questions lacked clarity, so I'll try to be clear as much as possible.我之前的问题不够清晰,所以我会尽可能地清楚。 I'm trying to create a weather app but every time I try to fetch information (JSON Format) it returns undefined.我正在尝试创建一个天气应用程序,但每次我尝试fetch信息(JSON 格式)时,它都会返回未定义。 I am using pure vanilla JavaScript and trying to load Open Weather Map's API.我正在使用纯香草 JavaScript 并尝试加载 Open Weather Map 的 API。 I tried using another API (Free Weather API) but that returned undefined as well.我尝试使用另一个 API(免费天气 API),但它也返回未定义。 Please note that the websites are loading properly I think its just a problem with my code.请注意,网站加载正确我认为这只是我的代码的问题。

fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric').then(function (response) {
    console.log('success!', response.main);
}).catch(function (err) {
    console.warn('Something went wrong.', err);
});

The way promise works, you need to transform the response and pass this transform through to the next then pipe. promise 的工作方式,您需要转换响应并将此转换传递给then一个 pipe。

fetch(
    'http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric'
  )
    .then(function (response) {
      return response.json();
    })
    .then(function (responseJSON) {
      console.log('success!', responseJSON.main);
    })
    .catch(function (err) {
      console.warn('Something went wrong.', err);
    });

Explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise说明: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

We should use json() method on the response object before doing any kind of operation on the data.在对数据进行任何类型的操作之前,我们应该在响应 object 上使用json()方法。 Actually json() method takes a Response stream and reads it to completion.实际上json()方法需要一个响应 stream 并将其读取完成。 It returns a promise.它返回 promise。 So for consuming the promise returned by response.json() we should use .then() method.所以为了消费由response.json()返回的 promise 我们应该使用.then()方法。 On resolving it parses the body text as JSON.解析时将正文文本解析为 JSON。

fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric')
        .then(function (response) {
           // parsing the body of response object
            return response.json();
        })
        .then(function (response) {
            console.log('sucess', response.main);
        })
        .catch(function (err) {
            console.warn('Something went wrong.', err);
        });

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

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