0

I have built API in Google Cloud Function. The CORS error occurs when I try to fetch API directly. Although I added Access-Control-Allow-Origin, it failed.

The error:

'https://xxxxxxx.com' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

const apiURL = 'https://xxxxxxx.com'

const headers = new Headers();
headers.set("Content-type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");

const createRes = await fetch(
  `${apiURL}/testFetch`,
  {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      test: "test"
    }),
  }
);

1
  • CORS has to be enabled on server side and not client side. Access-Control-Allow-Origin add to response header. Also sometimes * is not respected by browser so having exact URL as value may help. Commented Apr 20, 2020 at 8:41

1 Answer 1

2

Access-Control-Allow-Origin is a response header. It should be a part of your response, not the request. Please ensure that your API returns the corresponding header.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Sign up to request clarification or add additional context in comments.

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.