An Introduction to CORS

Rapid
An Introduction to CORS
An Introduction to CORS

An introduction to CORS.

Rapid
An Introduction to CORS
An Introduction to CORS

What is CORS? As a standard, all browsers implement a Same-Origin Policy for security reasons. This is where requesting data from the same origin is allowed, but requesting data from another URL throws an error. CORS (Cross-Origin Resource Sharing) is an HTTP-based mechanism that allows us to request data from other URLs.

Rapid
An Introduction to CORS
An Introduction to CORS

In its most basic form, a CORS request involves a request from the browser to another domain's server and that server responding successfully or unsuccessfully.

In the request, an 'Origin' header is sent declaring the domain making the request. The server responds and adds an 'Access-Control-Allow-Origin header in its response. If the origin here is the same as in the request, access to the resource is given.

Rapid
An Introduction to CORS
An Introduction to CORS

Some HTTP Methods (all except GET, POST, and HEAD) require a preflight request before the main CORS request is made.

A preflight request starts with the browser making an HTTP OPTIONS request to the server with the proposed request method of the main request in the 'Access-Control-Request-Method' header.

The server responds with an 'Access-Control-Allow-Method' header, stating the accepted request methods. If the method sent in the request matches here, the preflight request is accepted, and the main CORS request follows. If the method does not match, the entire request fails here.

Rapid
An Introduction to CORS
An Introduction to CORS

An example of a CORS request with a preflight request would be a website making an AJAX call to POST JSON data to a REST API.

Some preflight responses may contain an 'Access-Control-Max-Age' header specifying the time the response must be cached within. Using this header means the client won't need to send a preflight request every time it wants access to the CORS resource.