Fetch Error No ‘Access-Control-Allow-Origin’ Header – How to Fix

fetch-apijavascript

I'm using 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 face error in 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's mode to 'no-cors' to fetch the resource with CORS disabled.

I set headers for the second fetch:

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

error will gone but console.log(JSON.stringify(data)) do not log anything in console and the fetch not return any value.
what is the problem with my code?

Best Answer

The problem is not in your JavaScript code, it is in the API, the server doesn't support cross origin request, if you are the owner of this API you have to add 'Access-Control-Allow-Origin' header to the response with the allowed origins (* to allow from any origin). in some cases jsonp request may work.

Note: this problem happen only when the request is generated from the browser

Related Question