CORS

jamave
3 min readJul 13, 2021

So, let’s just dive into CORS. CORS is an acronym for Cross-Origin Resource Sharing. It’s a mechanism that allows one website on one URL to request data from a different URL.

some random website asking for data from another site

This could be something like you trying to use an image that’s hosted on another website, or you trying to fetch data from your API.

If this fails because of a CORS error, it’s because our browser implements the “Same-Origin Policy” as part of its security model. This basically allows a website to freely request images/data from its own URL, but blocks anything from an external URL, unless certain conditions are met.

When a browser makes a request, it adds an origin header to the request message:

If that request goes to a server on the same origin, then it’s allowed on the browser.

But if the request goes to a different URL,

Cross-origin request

this is known as a cross-origin request.

When sending the response, the server will add the Access-Control-Allow-Origin header. Its value has to match the origin in the request. Or, it could the ‘*’ which allows anything.

Loco, this accepts all
This was being sent by localhost:3001

If these two values DON’T match, the browser will block the response data from being shared to the client, which’ll result in an error in the browser.

If you’re not the owner of the server, you can’t really fix this error. If you are though, you can configure it to respond with the proper header. For example in rails:

In our rails app config/initializers/cors.rb

This is set to localhost but to follow the above examples it should be flat.com

--

--