我一直在开发一个小的react应用程序,它使用openWeatherMap应用程序接口来检索给定位置的当前天气状况。
当在我的系统上进行本地测试时,这个应用程序可以完美地工作。然而,当部署到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);
}
);
}
发布于 2021-03-16 18:06:56
这段代码似乎也适用于我。您可能需要使用https作为URL,因为浏览器会拒绝启用了https的网站上的http请求。
发布于 2021-03-16 02:57:04
事实证明,肯尼·约翰·雅各布在某种程度上是对的!(在某种意义上)。问题是在app url中使用了安全的http协议(由Heroku部署模块生成)。如果仅通过http访问应用程序,则api调用就像charm一样工作。我永远也猜不到这一点。还是要感谢雅各布
https://stackoverflow.com/questions/66636197
复制相似问题