javascript - 如何修复香草javascript中的cors错误?这是我的代码
问题描述
我正在制作天气应用程序,我试图从 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);
})
})
}
});
解决方案
可能有多种原因,但默认情况下,fetch
禁用 CORS 您可以添加fetch(api,{})
选项,如果不正确,则 URL 必须正确,TypeError: Only absolute URLs are supported
并且将请求转换为承诺对于等待浏览器提供坐标至关重要。
function getPosition() {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
async function main() {
var position = await getPosition();
let long = position.coords.longitude;
let lat = position.coords.latitude;
let secretApi = "b49f9f35788fbd19a06bc8d82140c40f"
let api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${secretApi}`;
fetch(api).then((response) => {console.log("res",response);
return response.json();
}).then(data => {console.log("data", data);
}).catch(err => console.log("err", err));
}
main();
推荐阅读
- r - R中分布的随机抽样速度
- python-3.x - 你如何在 Python 中输入两个类的联合列表作为参数
- javascript - 保护来自 Javascript 的 API 请求
- c++ - 无法在没有命名空间冲突的情况下定义友元函数
- python - 我有一个打开网站的程序,我将默认浏览器设置为 google chrome,但它仍然使用 Internet Explorer
- python - 从没有 for 循环的 2D 矩阵的行创建对角矩阵
- ffmpeg - 关于 ffmpeg 中的 h264_qsv 编码速度
- go - 在带有 Gorilla Mux 的路径中间不可能有路径参数吗?
- docker - 在 Dockerfile 中复制或添加后容器中不存在文件
- mysql - 如果过去 12 个月内没有记录发生,则 MySQL 选择查询