首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenWeatherMap API返回'undefined‘

OpenWeatherMap API返回'undefined‘
EN

Stack Overflow用户
提问于 2020-12-28 14:40:04
回答 2查看 332关注 0票数 1

我之前的问题不够清晰,所以我会尽量说清楚。我正在尝试创建一个天气应用程序,但是每次我尝试fetch信息(JSON格式)时,它都返回未定义。我使用的是纯JavaScript,并试图加载Open Weather Map的API。我尝试使用另一个API (自由天气API),但同样返回未定义。请注意,网站加载正常,我认为这只是我的代码的问题。

代码语言:javascript
复制
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);
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-12-28 15:15:19

promise的工作方式是,您需要转换响应并将此转换传递到下一个then管道。

代码语言:javascript
复制
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);
    });

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

票数 0
EN

Stack Overflow用户

发布于 2020-12-28 15:33:29

在对数据进行任何操作之前,我们应该在response对象上使用json()方法。实际上,json()方法接受一个响应流,并读取它直到完成。它返回一个承诺。因此,为了使用response.json()返回的promise,我们应该使用.then()方法。在解析它时,将主体文本解析为JSON。

代码语言:javascript
复制
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);
        });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65473835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档