因此,我正在尝试使用Open weather API构建一个简单的天气应用程序,这是我第一次尝试使用API构建任何东西。API密钥应该是有效的,但是当我尝试输入城市名称时,我在chrome控制台中不断收到这个错误。我的JavaScript在错误消息下面,我不确定是代码中的问题,还是我不知何故链接了错误的API键或基础的源代码。任何建议都将不胜感激!
(索引):1从源'http://127.0.0.1:5500‘获取'https://openweathermap.org/data/2.5/weatherweather?q=London&units=metric&APPID=’的访问已被CORS策略阻止:请求的资源上不存在' Access -Control-Allow- origin‘标头。如果不透明的响应满足您的需求,请将请求的模式设置为'no- CORS‘,以便在禁用CORS的情况下获取资源。
const api = {
key: "",
base: "https://openweathermap.org/data/2.5/weather"
}
const searchbox = document.querySelector('.search-box');
searchbox.addEventListener('keypress', setQuery);
function setQuery(evt) {
if (evt.keyCode == 13) {
getResults(searchbox.value);
console.log(searchbox.value);
}
}
function getResults (query) {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(weather => {
return weather.json();
}).then(displayResults);
}
function displayResults (weather) {
console.log(weather);
}
发布于 2021-04-22 11:40:19
这是CORS错误。跨域资源共享是一种基于HTTP标头的机制,它允许服务器指示浏览器应允许从其自身以外的任何来源加载资源。
现在,回到您的问题,一个简单的解决方案是使用CORS代理。您可以使用以下命令-
https://cors-anywhere.herokuapp.com/http://api.openweathermap.org...
此外,如果不确定这是否有效,您可以检查在您的API设置中是否有允许IP地址的选项。如果是,则将localhost添加到该列表中。
https://stackoverflow.com/questions/67212413
复制