Skip to content
Advertisement

Cloudflare workers CORS ignored

I created a SendGrid form using CF Workers and set (for testing) Access-Control-Allow-Origin”, ‘*’ but it’s being ignored on the frontend:

Access to XMLHttpRequest at 'https://<domain>.workers.dev/' from origin 'https://<frontend-domain>.dev' 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.

Do I need to also add it to the AXIOS POST request?

Here’s code from my workers file:

const myHeaders = new Headers();
  myHeaders.set("Access-Control-Allow-Origin", '*');
  myHeaders.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
  myHeaders.set("Access-Control-Max-Age", "86400",);
  return new Response((emailResponse.ok), {status: 200, headers: myHeaders}) 

And here’s the AXIOS request:

this.$axios.$post(
  "https://<domain>.workers.dev/",
  {
    name: this.mailData.name,
    eMail: this.mailData.eMail,
    phone: this.mailData.phone,
    message: this.mailData.message,
  },
  {
    headers: {
      "Content-Type": "application/json",
    },
  }
);

It all works fine using Insomnia and the headers are visible there: enter image description here

Advertisement

Answer

You’ve correctly set the headers on the response to the POST itself. However, before the browser even sends the POST, it uses a “preflight request” to check whether cross-origin POSTs are allowed. The preflight request is an OPTIONS request, using the same URL. You will need to respond to OPTIONS requests as well, with the same access control headers, and status code 204 (no content).

See the MDN documentation on preflight requests.

Alternatively, if your application will accept the POST request using Content-Type: text/plain instead of Content-Type: application/json, then that will avoid the need for a preflight request, because Content-Type: text/plain qualifies as a “Simple Request” and therefore does not require a preflight.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement