【问题标题】:How to fix cors error in vanilla javascript? Here is my code如何修复香草javascript中的cors错误?这是我的代码
【发布时间】: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


【解决方案1】:

可能有多种原因,但默认情况下,fetch 会停用 CORS,您可以添加 fetch(api,{}) options,如果不是 TypeError: Only absolute URLs are supported,则 URL 必须正确,并将请求转换为 promise 必须等待浏览器提供坐标。

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();

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2021-01-01
    • 2023-01-20
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2018-11-19
    • 2019-12-04
    • 2012-09-23
    相关资源
    最近更新 更多