【问题标题】:Failed openWeatherMap API callopenWeatherMap API 调用失败
【发布时间】:2021-06-12 14:43:33
【问题描述】:

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

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

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

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

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

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

提前谢谢你。

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

这里是完整的 fetch 函数:

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

【问题讨论】:

  • 能否展示完整的 fetch 功能?
  • 已编辑以包含完整的提取功能
  • 这段代码似乎也适用于我。我认为您需要对 URL 使用 https,因为浏览器会拒绝启用 https 的网站上的 http 请求
  • 事实证明——肯尼·约翰·雅各布在某种程度上是对的! (某种意义上)。问题是在应用程序 url 中使用了安全的 http 协议(由 Heroku 部署模块生成)。如果仅使用 http 访问应用程序,则 api 调用就像魅力一样工作。一百万年我都猜不到这一点。谢谢雅各布
  • 从您的评论中,我了解到您为您的网站禁用了 https,是吗?以后如果你做任何涉及敏感数据的应用程序,你应该坚持完全使用https :)

标签: reactjs api github heroku openweathermap


【解决方案1】:

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

【讨论】:

  • 我可以将我的评论改写为答案,您可以将其标记为正确答案,以便其他人轻松识别。
【解决方案2】:

这段代码似乎也适用于我。您可能需要对 URL 使用 https,因为浏览器会拒绝启用 https 的网站上的 http 请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2014-02-15
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多