Cross-Origin Resource Sharing (CORS) is a mechanism for requesting fonts, scripts, and other resources from an origin (defined, as above, as the combination of domain, protocol, and port) other than the requesting origin. For instance, if sending a request from http://www.example.com, any of the following would be "cross origin":
- http://mail.example.com (domain differs),
- https://www.example.com (protocol differs),
- http://www.example.com:8080 (port differs),
and, thus, scripts (or font, or other similar resources) would be blocked from these "foreign" sites. CORS offers a way for two sites to allow safe sharing of resources.
How CORS Works
CORS defines the communication between browser and server: specific headers in the HTTP request and HTTP response tell the browser that its OK to accept the resource. At its most basic, a server issuing an HTTP response which includes the header
is allowing access from all requesting domains. A more-restrictive response, for example
would allow access only from a particular domain.
The great thing for us, as web developers, is that CORS-enabled responses work just like responses from our own (same-origin) site: our code can process the JSON, XML, or other response we receive just as if we were making a request of a page or resource on our own server.
The CORS request/response cycle can get significantly more complex, with "preflight" requests sent by the browser and responded to from the server, before another set of request/response; the passing of cookies or other authentication mechanisms; and other sharing of data. Check out https://www.html5rocks.com/en/tutorials/cors/, an excellent tutorial on HTML5 Rocks, to delve deeper into the topic.
Check out http://enable-cors.org/resources.html#apis for a list of sites that offer CORS-enabled resources.
Let's look at an example, accessing a CORS-enabled site and a not-CORS-enabled site. Open CORSJSONP/Demos/cors-html5-rocks.html in your browser and in a code editor to review the code. No need to start the Node.js server for this example.
In large part, CORS depends on the server responding with the appropriate headers; if that is the case then, conveniently, our work as client-side developers becomes relatively easy, pretty much the same as if we were working with resources on our own server.
Let's have you try out a call to a remote data source that sends back CORS-enabled headers.