Fetch error No header "Access-Control-Allow-Origin" is present on the requested resource

I use the fetch API to get data from other APIs, this is my code:

var result = fetch(ip, {
        method: 'get',
    }).then(response => response.json())
      .then(data => {
        country = data.country_name;
        let lat = data.latitude;
        let lon = data.longitude;                       
        //fetch weather api with the user country
        return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`);
    })
    .then(response => response.json())
    .then(data => {
        // access the data of the weather api
        console.log(JSON.stringify(data))
    })
    .catch(error => console.log('Request failed', error));

but I ran into an error in the console:

Fetch API cannot load https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/52.3824,4.8995. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request mode to 'no-cors' to fetch the resource with CORS disabled.

I set the headers for the second sample:

return fetch(`https://api.darksky.net/forecast/efc76f378da9a5bd8bb366a91ec6f550/${lat},${lon}`, {
  mode: 'no-cors',
  header: {
    'Access-Control-Allow-Origin':'*',
  }
}); 

the error disappears, but console.log(JSON.stringify(data))writes nothing to the console, and fetch returns no value. what is the problem with my code?

+4
source share
1 answer

JavaScript-, API, , API, "Access-Control-Allow- Origin ' (* ). jsonp .

: ,

+3

Source: https://habr.com/ru/post/1676560/


All Articles