-1

I'm making a POST request to my API but getting returns a 'blocked by CORS policy' message.

The API is expecting a XML data which I have contained in a XML file which is being imported in to this request in the exampleAccountSettings value in the code example below.

The message I'm currently getting being returned from the API is this

Access to fetch at 'https://exampleAPI.com/api/settings/import' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

And here's my Promise

    return new Promise((resolve, reject) => {
      const requestUrl = https://exampleAPI.com/api/settings/import;
      const init = {
        method: 'POST',
        mode: 'cors',
        headers: {
          authorization: localStorage.token,
          "Access-Control-Allow-Origin": "*",
        },
        body: JSON.stringify(exampleAccountSettings)
    };
    return fetch(requestUrl, init).then((response) => {
      log.debug('importAccountSettings(): response:', response);
    })
  });

All I've seen similar to this question state I need to add something like "Access-Control-Allow-Origin": "*" to specify that access is allowed but this seems to have no effect.

So is there a different approach for ES6 / React or maybe it's something I have misunderstood? Any advice welcome or if someone can point me in the direction of some research I'd be very appreciative!

Neil Kelsey
  • 811
  • 4
  • 13
  • 31

1 Answers1

1

You need to be able to control the server-side response headers from https://exampleAPI.com. If you don't own the domain or can't control the headers, then you're out of luck.

For security reasons, JavaScript can only make xhr calls to the same domain (or cross-domain if the right header Access-Control-Allow-Origin is present and allows your domain - or wildcard *).

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

jsdeveloper
  • 3,945
  • 1
  • 15
  • 14