CORS

Last Updated Aug 07, 2021

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.

When we're setting up an AJAX call, we use the `XMLHttpRequest` object to request data from a Web Server and the HTML DOM to display or use the data. This is a GET API call. JavaScript, however, can only make calls to URLs that live on the same origin as the location where the script is running. CORS allows us to add special headers (access-control-allow-headers) that relax the same-origin rule, and tell the browser "Hey, it's OK if the cross-origin requests are coming from these listed origins."

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:

```jsres.setHeader("Access-Control-Allow-Origin", "https://yoursite.com");```

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".

Preflight Request

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

Conclusion

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.