CORS: Basics Explained

·

2 min read

CORS lets a web page in a browser get data from or send data to a web server elsewhere. CORS is a rule set built on HTTP.

A CORS request is when the web page gets or sends data this way. CORS requests are special HTTP requests.

CORS is a rule that only affects web pages in a browser. HTTP clients that are not web browsers ignore CORS when sending CORS requests. For example, CORS does not affect someone making a CORS request via a command-line HTTP tool like cURL.

CORS is like a deal between a web page and a web server. The server says which place a web page in a browser can request from. The web page follows the server's CORS rules. A CORS request is okay only if the web page's place matches the server's place. A server with no stated place and a page with a non-matching place both mean the CORS request is not okay. Web browsers stop web pages from sending not okay CORS requests.

CORS stands for Cross Origin Resource Sharing.

Cross means different. Cross refers to the web page and the web server running on different origins or places.

Origin is the place that the web page or web server is running at. The link or URL part before the first non-double forward slash character is the origin. Three parts make up the origin: the Internet protocol or scheme, the domain name, and the port number. https://example.com:443 is an example of an origin. The port is an optional part of the origin. If you omit the port, the web server assumes the default port for the given scheme. For example, the server assumes the origin http://example.com has the port 80 because 80 is the default port for HTTP.

Resource is the target of an HTTP request. A resource is any digital content accessible on the web server via HTTP. Resource examples include HTML documents, digital image files, JavaScript script files, etc.

Sharing means the web server gives data access to the web page in the browser.

A web server must add the correct HTTP headers to its responses to allow CORS requests. The server needs at least the Access-Control-Allow-Origin header in its responses for CORS. This header should be set to * or the origin that the web page is running from. * means web pages from any origin can make CORS requests from the server. The first header value * is a security risk and you should not set this on production web servers.

References: