Disclaimer: If you are here for an in-depth solution to a CORS issue, I would suggest checking out this video for Express.js or this video for Ruby on Rails. This article intends on being a high-level look at what CORS is, and how it works.
If you have ever fetched data from an API (being that a public one or your own), chances are that you have at some point run into a funny little error in your console:
While annoying to see, these errors are often quite easy to fix (see links above). But really, what is it saying? What is CORS?
Cross-Origin Resource Sharing
CORS stands for Cross-Origin Resource Sharing. As can be inferred by its name, CORS is a mechanism that allows a website at one URL to request data from a different URL. It helps to regulate who can access and affect data on the server-side URL, and what permissions this accessor is given.
Why CORS?
As part of its security model, your browser implements a Same-Origin Policy. This allows the website to fetch data from its own URL, but blocks any data from an external URL unless certain conditions are met. As mentioned, the aim of restricting access by the request URL is to prevent unwanted access to server-side data.
How is CORS enabled?
Modern browsers block cross-origin requests by default, however, this can be changed by configuring the server to respond with the proper header (Assuming that you have access to this server). When requesting data, the client adds an "Origin" header with the URL of the client to its request message. In the server's response, we will see an "Access-Control-Allow-Origin" header, like this one:
Access-Control-Allow-Origin: localhost:3000
The value of this header must match the Origin header in the request, like so:
Origin: localhost:3000
If our origins match on both sides, chances are that we will not be hitting a CORS error. However, depending on the HTTP method in your request, you may still be blocked.
Preflighting
In addition to limiting which client URLs have access to it, the server also limits what actions are possible with a request. Sure, you may be comfortable with letting certain sites access the data on your server in order to view it, but do you really want to let them add or delete data?
This is where preflighting comes in. Any requests containing HTTP headers like PUT, PATCH, or DELETE will be subject to a preflight check that ensures that the given header is allowed. Like before, if the given header is accepted, the client-side will receive a response that looks like this:
204
Access-Control-Allow-Origin: localhost:3000
Access-Control-Allow-Methods: PATCH
Now say that your server wants to set a limit to how long the client can access its data before having to send out a new request. This can be done using Preflight Caching, which will look like this:
Access-Control-Max-Age: 64800
Resources
This has been a very brief overview of what CORS is and how it functions. To learn more about CORS, I suggest checking out the following resources: