3

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.

4
  • 1
    Please add the actual fetch code as a minimal reproducible example? Commented Jul 19, 2021 at 15:42
  • Does this answer your question? Enable CORS in fetch api Commented Jul 19, 2021 at 15:53
  • 1
    You need to add those headers to the server response at url, you can't do it from the fetch request. Commented Jul 19, 2021 at 15:56
  • You have to set this header at server in the response. Not in the request. 'Access-Control-Allow-Origin' : '*' Commented Jul 19, 2021 at 16:15

3 Answers 3

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: *");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.