DEV Community

Hyunjin Cho
Hyunjin Cho

Posted on

April 5th, 2022

*CORS *
Cross-Origin Resource Sharing

a HTTP header based mechanism used when requesting resource to another origin from an origin

origin : like address for server

https://google.com:80

protocol : https://
host : google.com
port : :80

the system that compare origins is activated under browser. That is, when the server receives the request from another origin, the server sends response unless there is a restriction that the server will take request from same origin. Then, browser will compare the response whether CORS is violated or not.

browser : https://hyunin.com
server : https://server.com

  1. send request to server
  2. send response to the browser
  3. the browser check if the origin is different or not. If different, the response is thrown.

Because of that, this CORS does not work between server communication.

Working of CORS

when requesting resources from another origin, the application-browser- use HTTP protocol and the request header includes Origin with value

Origin: https://hyunjin.com

then when the server send response, the response header includes Access-Control-Allow-Origin with allowed value. The browser will compare ACAO and request origin

1. when requesting preflight

preflight means the pre-request before actual request for checking if it is safe to send request. For this, OPTIONS method is used.

browser send pre-request(OPTIONS/resources - Origin:https://hyunjin.com) to the server
the server send response(200 ok Access-Control-Allow-Origin: *) to the browser.
browser send actual request to the server
the server send response

more specifically,
In preflight,
there are origin, Access-Control-Request-headers, Access-Control-Request-Method
In the response to the preflight,
there are Access-Control-Allow-Origin

2. simple request

No preflight and others are same

the condition for this,

  1. the request method should be one of GET, HEAD, POST
  2. only Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, Width should be used
  3. when content-type, application/x-www-form-urlencoded, multipart/form-data, text/plain

resource: https://evan-moon.github.io/2020/05/21/about-cors/

Top comments (0)