首页 > 解决方案 > 如何修复香草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);
            })
        })
    }
});

标签: javascriptfrontendweb-development-server

解决方案


可能有多种原因,但默认情况下,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();

推荐阅读