DEV Community

Cover image for CORS - As Simple As Possible
Mattias Velamsson
Mattias Velamsson

Posted on

CORS - As Simple As Possible

Today, I ran into a CORS error while working on a project so I decided to dig a bit deeper into what it is, and why it happened. Now, a lot of the articles I found are pretty complex, so I decided to give a go at describing it in a short, concise way how it works.


A technology to specify which domains can access a servers resources.


You can read more about it here:


A request gets sent to access something (in this example an image on my portfolio).

<img src="" />
Enter fullscreen mode Exit fullscreen mode

Server checks the request and it’s header.

Request ✅ 
It will respond with a 200(OK!) and the image will display on your site.


Request ❌ 
It will respond with a 5xx(DENIED!) and the image will appear broken, and you will have a status code in your console.

CORS error console



The simple answer is usually one of two:

  • The type of request (method) you are sending is not allowed. GET / PATCH / POST / DELETE

  • Typos in your URL

I solemnly swear I have quadrouple-checked the two options above.

  • CORS is not enabled on the server (if you’re not the owner, tough luck. Journey ends here.)

It is enabled but still doesn’t work?

  • Open the console > Network > Your Request and double check that you can see “Access-Control-Allow-Origin header” in the list.

developer console.png

  • If not, you need to add middleware.
  • If it is but doesn’t work, check if it is a non-standard HTTP request (not GET, PUT, PATCH, DELETE) and you’ll need to add them.

I checked everything?

  • Sometimes errors thrown in your project are displayed as text, and when the server outputs them it actually throws in headers as well that in turn will trigger CORS policy. And even if the server error does not print as text but is handled via an HTTP code that is not 200, you will also get the CORS policy error.


The keys you throw into your CORS policies, stating what is allowed and what is not. It allows you to customize it.


With Preflight you can add extra options such as checking if the request you want to do is allowed and ok or not, before sending the request. Now, this can also be cached in Preflight Cache with a TTL(Time To Live). You can read more about it here:

Alright. There’s obviously way more abut this, but this is a quick overview. Ciao!

Latest comments (0)