Cross-Domain Requests and CORS

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.

Same-Origin Policy

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

HTTP requests from Javascript are bound by the Same Origin Policy

Basically, AJAX requests must have the same origin (domain and port).

There are three common work-arounds:

  1. JSONP
  2. Proxying
  3. 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.

  1. CORS supports HTTP methods other than GET
  2. CORS has access to HTTP status codes and the response body
  3. CORS supports many types of authorization (Basic Auth / OAuth). JSONP only supports cookies.

Further reading: https://developer.mozilla.org/en-US/docs/Web/HTTP/AccesscontrolCORS#Access-Control-Allow-Origin

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!