Update: 10/24/2016 This resource has also been really helpful and also has this handy diagram for all those visual learners =) https://www.html5rocks.com/en/tutorials/cors/
I was working with an API, where I was attempting to issue an AJAX GET request to retrieve some JSON, but ended up encountering this error:
XMLHttpRequest cannot load http://external-domain/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my-site' is therefore not allowed access.
What I found out was that my request to the API was violating the Same-Origin Policy (SOP). SOP is a security measure in browsers to restrict certain interaction between documents (or scripts) that originate from different origins.
SOP is aimed to prevent malicious scripts from reading data (cookies / localStorage, etc.) from you domain and to prevent the scripts from sending it to their servers.
SOP restricts Cross-Origin HTTP requests
Cross-Origin writes are apparently allowed, but Cross-Origin reads are not.
So, I can make an HTTP request from my site to a cross-domain site, and the external site will successfully receive this request (this is considered a “write”). However, the script residing on my site will not be able to read any data returned from the cross-domain site (this is considered a Cross-Origin “read” and is blocked by the browser).
Basically, AJAX requests must have the same origin (domain and port).
There are three common work-arounds:
- Cross-Origin Resource Sharing (CORS)
CORS is the Preferred Solution
CORS allows for cross-domain AJAX requests through using HTTP headers to control access to the remote resource.
- CORS supports HTTP methods other than GET
- CORS has access to HTTP status codes and the response body
- CORS supports many types of authorization (Basic Auth / OAuth). JSONP only supports cookies.