DEV Community

Shashank Trivedi
Shashank Trivedi

Posted on

CORS(Complete-Guide)

By default, browser follow same origin policy and it blocks all cross-origin communications. example if user is browsing on https://abc.com and wanted to load resources from https://xyz.com by default it is not allowed. This is browser’s same origin policy.

Cross Origin Resource sharing or CORS is http header-based mechanism to communicate with different origins.

An origin is made up of PROTOCOL : DNS :PORT

If Protocol is different than origin is different . if DNS is different ,origin is different , if Port is different ,origin is different. Example
o http://abc.io & https://xyz.io are different origin.
o http://localhost:5000 and http://localhost:3000 are different origin.

Access-Control-Allow-Origin : if you set Access-Control-Allow-Origin header as * all cross-origin communication is possible. But this is not recommended because of security reasons. Better to declare only origins which should be allowed to communicate in place of *. Example if a user is browsing on https://abc.com and wanted to load resources from https://xyz.com to enable cross origin communication ,declare Access-Control-Allow-Origin : https://abc.com on the server of https://xyz.com.

Preflight request : Browser make an additional OPTIONS network call in case of PUT, DELTE, POST cross origin requests. This request is called preflight request.

Preflight request will have Access-Control-Request-Method header. Example if http://abc.com wants to update data on http:// xyz.com . The preflight request will have Access-Control-Request-Method : Put

Preflight response will have Access-Control-Allow-Methods header. It will have all the methods which are allowed.

CORS preflight communication

By default, cookies are blocked on browser . to make it work we need to set Access-Control-Allow-Credentials as true in response header.

Top comments (0)