0

I was making weather application and i was trying to fetch data from API but i am getting CORS error again and again please help me solve this. Thank you!

//adding event lisitener to ask location

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);
            })
        })
    }
});
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • I've seen about this issue popping up from time to time with openweathermap's API. You can try to add a cors overwrite url, by changing the url to: `https://cors-anywhere.herokuapp.com/http://api.openweathermap.org...` – Ant Jun 13 '21 at 12:47
  • Does this answer your question? [Weather API request cors error](https://stackoverflow.com/questions/41215140/weather-api-request-cors-error) – Ant Jun 13 '21 at 12:48

1 Answers1

0

It can be for several reasons, but by default, fetch deactivates CORS you can add a fetch(api,{}) options, the URL must be correct if not TypeError: Only absolute URLs are supported and converting the request into a promise is essential to wait for the browser to provide the coordinates.

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();
Hamada
  • 1,836
  • 3
  • 13
  • 27