What is CORS?
Cross-origin resource sharing, or CORS, is an HTTP header-based mechanism originating from a server. The server indicates that other domains, schemes, or ports other than its own should permit resource loading.
CORS Preflight Special Headers
CORS extends HTTP and adds two special headers.
Access-Control-Allow-Origin response header
This header tells the browser what origins are allowed to receive requests from this server. The origin responsible for serving resources will need to set this header. The line of code we're interested in looks like this:
This is telling our browser, "https://yoursite.com" may receive requests from this server. This header will have to be set by the owner of "https://yoursite.com".
The preflight request is a little more complex, but is basically asking the server before sending the request, "Can I do this?"
Before sending the actual request, the browser will send what we call a preflight request, to check with the server if it allows this type of request. A preflight request is an OPTIONS request which includes the following headers:
- origin - The `origin` header cannot be changed programmatically, but is added by configuring your server configuration to allow CORS requests. You can learn more about the `origin` header here.
- access-control-request-method - tells the server which HTTP method the request implements
- access-control-request-headers - tells the server which headers the request includes
CORS allows AJAX and React developers to seamlessly update parts of themselves from a web server that is not the web server the request originated from. This is a powerful additional tool for their development toolkit. It requires a bit of a security work-around, but it's safe to use, and its benefits are worth it.