【问题标题】:OpenWeatherMap API returning 'undefined'OpenWeatherMap API 返回“未定义”
【发布时间】:2020-12-28 06:40:04
【问题描述】:

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

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

【问题讨论】:

  • 我刚刚从我的 API 密钥库中删除了我在代码中使用的那个 API 密钥。换句话说,该 API 密钥将不再起作用。
  • 我不确定你的意思,但是当我在浏览器中打开链接时,它会显示一个 JSON 文件,显示我需要的所有数据。

标签: javascript json openweathermap


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在对数据进行任何类型的操作之前,我们应该在响应对象上使用json() 方法。实际上json() 方法需要一个响应流并将其读取完成。它返回一个承诺。所以为了消费response.json()返回的promise,我们应该使用.then()方法。解析时将正文文本解析为 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);
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 2013-10-09
      • 1970-01-01
      • 2020-09-26
      • 2020-11-06
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多