Skip to main content

What is CORS (Cross Origin Resource Sharing)?

· 3 min read
3sam3
Backend Developer

What is CORS?

CORS (Cross-Origin Resource Sharing) is a system, consisting of transmitting HTTP headers, that determines whether browsers block frontend JavaScript code from accessing responses for cross-origin requests.

ㄴ️Technically, that is the definition of CORS, but down below is what I think.

Mechanism to block unwanted requests in browser.

Preflight Request?

Before discussing how CORS cuts off unwanted requests, we have to talk about what a preflight request is.

I'll try to make it short.

d2

If you make an actual request (by event or something), the browser makes a pre-request to see if the server is aware of using specific methods and headers.

This is basic behavior browser does before it makes a request.

By using this, we can avoid server running which we're not going to take data from and can ensure safety (by getting only getting data from known sources).

Without Preflight Request

d2

Using Preflight Request

d2

How CORS Works

browser verifies whether origin is allowed in Access-Control-Allow-Origin field of header in response.

This checks whether protocol + host + port is the same or not. (Same Origin Policy)

protocolhostportpathquery stringfragment
https://google.com:443path?name=sam#cache

How to deal with CORS?

  • Modify server to return Access-Control-Allow-Origin field in response.
    • Try not to use *. This could possibly cause serious security issues.
  • Use a Reverse proxy of Webpack Dev Server.

References