16

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Mi La
  • 309
  • 1
  • 2
  • 8

2 Answers2

29

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

  • 3
    This was the right answer for me as well. This other answer gives some details on the specific CORS headers you can use: https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – mojave May 02 '18 at 03:44
16

The issue will not present when "no-cors" argument is used after the url

fetch(url, {mode: "no-cors"})
Chamod Pathirana
  • 713
  • 8
  • 16
  • 1
    I tried your code but my response will return empty, I don't know why it is occuring, can you give me your feedback? – huykon225 May 07 '20 at 02:35
  • 8
    Saying this can "fix" anything is misleading. All this does is give you an empty response instead of an error, for whatever that is worth. @huykon225 see https://stackoverflow.com/a/35291777/6221448 – AFOC May 18 '20 at 02:19
  • Note that `mode: "no-cors"` only allows a limited set of headers in the request. So you can't use "Authorization" header for example. [Source](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) – Burak Kaymakci Oct 10 '21 at 20:14
  • Note that this will not work with PUT requests – anthonyjdella Feb 06 '23 at 19:32