首页 > 解决方案 > openWeatherMap API 调用失败

问题描述

一直在开发一个小型反应应用程序,该应用程序使用 openWeatherMap API 来检索给定位置的当前天气状况。

在我的系统上进行本地测试时,该应用程序可以完美运行。但是,当部署到 Github 和 Heroku 时,它无法返回结果。

我几乎尝试了所有方法,但没有办法。我什至将 API 调用硬编码到浏览器的地址栏并返回结果,但是当相同的搜索字符串被硬编码到应用程序中时,调用失败了!

有人知道我在这里做错了什么吗?

这是进行 API 调用的代码块(带有硬编码参数):

fetch(
     "http://api.openweathermap.org/data/2.5/weather?units=metric&q=durban&appid=d6e0e85a41968aaf6240b5ed27522ebd"
   )

先感谢您。

注意:返回的错误是:获取失败

这是完整的获取功能:

  function getForecast(e) {
    e.preventDefault();
    // Next, make the call to the openweathermap API, with the parameters for the specified city
    // fetch(
    //   `http://api.openweathermap.org/data/2.5/weather?units=${unit}&q=${city}&appid=${keys.openweathermap_API_KEY}`
    // )
   
fetch(
     "http://api.openweathermap.org/data/2.5/weather?units=metric&q=durban&appid=d6e0e85a41968aaf6240b5ed27522ebd"
   )

      .then((response) => response.json())
      .then(
        (response) => {
          setResponseObj(response);
        },
        (error) => {
          alert("Error in fetching weather data : " + error.message);
        }
      );
  }

标签: reactjsapigithubherokuopenweathermap

解决方案


事实证明——肯尼·约翰·雅各布在某种程度上是对的!(某种意义上)。问题是在应用程序 url 中使用了安全的 http 协议(由 Heroku 部署模块生成)。如果仅使用 http 访问应用程序,则 api 调用就像魅力一样工作。一百万年我都猜不到这一点。还是谢谢雅各布


推荐阅读