KIM COMPUTER


Understanding CORS (Cross-Origin Resource Sharing)

CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.


1. Background: Same-Origin Policy (SOP)

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. This is called the Same-Origin Policy (SOP). * Definition of Origin: An origin is defined by the protocol, host, and port. Only if all three match exactly is it considered the "same origin."


2. Why CORS is Necessary

Modern web applications often request resources from different domains (e.g., a frontend at my-site.com calling an API at api.other-site.com). Since SOP blocks this by default, CORS provides a way to safely allow these cross-origin requests.


3. How it Works: Preflight Request

In many cases, the browser sends an initial "check" request using the OPTIONS method before the actual request. This is known as a Preflight Request.

  1. Client: "I want to send a request from my-site.com. Is it allowed?" (Header: Origin)
  2. Server: "Yes, I allow requests from my-site.com." (Header: Access-Control-Allow-Origin)
  3. Browser: Once confirmed, it sends the actual data request.

4. Common Solutions

To fix CORS errors, the server must be configured to return specific headers: * Access-Control-Allow-Origin: Specifies which origins are allowed (e.g., https://my-site.com or *). * Access-Control-Allow-Methods: Lists permitted HTTP methods (GET, POST, etc.). * Access-Control-Allow-Headers: Lists permitted custom headers.