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":
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. CORS defines the communication between browser and server: specific headers in the HTTP request and HTTP response tell the browser that it's 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 http://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.
For these examples to work, more files are required than are available in this how to. To see these examples in action, take the Ajax training course.
scripttag, and use jQuery to effect our Ajax calls.
btnnytimes, respectively, and use jQuery to listen for a click on each button.
h2tag's content to show from which source we receive the external data and setting the contents of
#ResponseContent div, if successful in our Ajax call, to the contents of the first
articletag from our received response.
articleto the contents of the first
articlefound in the returned response and display the contents on our page.
Access-Control-Allow-Origin: *response header that tells our browser it is OK to allow this Ajax call:
.fail(), which we chain on to the end of the $.ajax call to http://www.nytimes.com/, generates a popup alert. If we inspect the response headers, we would find no
Access-Control-Allow-Origin: *among them. If we check the console, we find that our browser complains of our attempt to violate the same origin policy: