【发布时间】:2021-08-29 15:33:02
【问题描述】:
我正在制作天气应用程序,我试图从 API 获取数据,但我一次又一次地收到 CORS 错误,请帮我解决这个问题。谢谢!
//添加事件监听器来询问位置
window.addEventListener("load", () => {
let long;
let lat;
//getting geolocation and current position
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
//API for weather websites.
let api = api.openweathermap.org/data/2.5/weather?
lat=${lat}&lon=${long}&appid=b49f9f35788fbd19a06bc8d82140c40f;
//fetching data from api
fetch(api).then((response) => {
return response.json();
})
.then(data => {
const { name } = data;
const { feels } = data.main;
const { id, main } = data.weather[0];
//Manipulating DOM
loc.textContent = name;
climate.textContent = main;
tempvalue.textContent = Math.round(feels - 273);
})
})
}
});
【问题讨论】:
-
我看到 openweathermap 的 API 时不时会出现这个问题。您可以尝试添加一个 cors 覆盖 url,方法是将 url 更改为:
https://cors-anywhere.herokuapp.com/http://api.openweathermap.org... -
这能回答你的问题吗? Weather API request cors error
标签: javascript frontend web-development-server