-1

Now, I am trying to make a fetch API call to a server. Something like

const response = fetch(request, {
        method: 'GET',
        mode: 'cors',
        headers: {
            // "Content-Type": "application/json;charset=utf-8"
            // "Access-Control-Allow-Origin": "*"
        }
    })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(error => console.log(error));

so the network call goes through and I get a 200 response but it gives me the error:

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. on my console and TypeError: Failed to fetch.

So just to test a fix for this really quick I tried to add the ACAO header (uncommenting the headers I have) but that sends an OPTIONS request which give a 405 (method not allowed) response AND the exact same errors as previously.

If someone could help with this I would love you forever, thanks.

Red
  • 1
  • 3

1 Answers1

0

you browser try to make an API call to something on different host and/or port. So the CORS mechanism ensure that nothing is wrong.

Your API (the server) must send the response header 'Access-Control-Allow-Origin' and probably some others.

If you request is not a GET, or contains any header (most of them), you're server must allow them by responding with header 'Access-Control-Allow-Headers'.

Also, if you want to see response headers in you browser JS Code, server must send 'Access-Control-Expose-Headers'.

This mechanics is a protection implemented by all current browsers.

Take a look at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

farvilain
  • 2,552
  • 2
  • 13
  • 24