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:

JavaScript

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

Here’s code from my workers file:

JavaScript

And here’s the AXIOS request:

JavaScript

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