1

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.

Mahsa az
  • 61
  • 1
  • 1
  • 5

3 Answers3

3

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: *");
2

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

Manish Kumar
  • 595
  • 2
  • 15
1

CORS is configured through server-side, so you need to configure on your File Hosting Server

Vengleab SO
  • 716
  • 4
  • 11