reactjs - 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);
}
);
}
解决方案
事实证明——肯尼·约翰·雅各布在某种程度上是对的!(某种意义上)。问题是在应用程序 url 中使用了安全的 http 协议(由 Heroku 部署模块生成)。如果仅使用 http 访问应用程序,则 api 调用就像魅力一样工作。一百万年我都猜不到这一点。还是谢谢雅各布
推荐阅读
- angular - 如何在非父子组件之间共享数据
- java - 如何与具有 Hibernate、JPA 复合键的不同实体建立一对多关系?
- entity-framework - Azure 函数中实体框架的连接字符串
- typescript - 如何在 TypeScript 中为函数参数设置参数名称和类型?
- ios - VERBOSE-2:Platform_view_layer.cc(28) - 尝试嵌入平台视图,但 PaintContext 不支持嵌入
- react-native - 使用 React Native 向特定用户推送通知
- ios - 在 Swift 中用手轻扫平滑解雇
- reactjs - 如何使用单元格渲染器中的按钮删除 ag-grid 行
- javascript - 将焦点大纲设置在复选框上包含标签上
- java - JavaFX 从 SQL 查询填充组合框