'How to resolve CORS error in Fetch API js

I want to fetch json from my subdomain (File Hosting Server) , but it gets the following error:

Reason: CORS request did not succeed)

(Reason: CORS header ‘Access-Control-Allow-Origin’ missing

my similar code:

async function getData(url = '', data = {}) {
    const response = await fetch(url, {
    method: 'get',
    mode: 'no-cors',
    headers: {
       'Access-Control-Allow-Origin' : '*'
    },
  });
  return response.json();
}

I add

headers: {
}                               'Access-Control-Allow-Origin' : '*'

but don't work.

I add

mode: no-cors

to code, fetch file but return response status 0 , mode: 'opaque'.

please help me.



Solution 1:[1]

I believe you know what you are trying to achieve here. Fetch with CORS use case is very tricky. CORS is driven by server settings. All the headers ACCESS-CONTROL-* are set at the server end.

Access-Control-Allow-Origin is for CORS, and the client honor this header when dealing with the cross-origin request. The server sends this header in the response. From the server end, you have to pass this header. In your response, you have to pass this header.

Access-Control-Allow-Origin: *

Or if you are dealing with credentials (Wild card not supported here):-

Access-Control-Allow-Origin: https://foo.example 

Reference:-

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Solution 2:[2]

if your host a PHP file file what you went to call in a other PHP file you will need lot of times to add this code in the PHP file thet you want to call at line_2

header("Access-Control-Allow-Origin: *");

Solution 3:[3]

As mentionned by Jim in the comments sections, you are looping over all books declared on line before, which by the way is an empty slice (so you won't loop at all).

Though in a for loop over a range, the first argument is the index of the current element. With, that you can fix a condition in your loop to exit it if you overflow your arbitrary limit

// books is a slice of Book -> []Book
for i, book := range books {
    // If you are on the eleventh element of your slice
    if i == 10 {
        // leave the loop
        break
    }
// Do whatever you want with book
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manish Kumar
Solution 2
Solution 3 Zyigh