Cross-Origin Resource Sharing

16 Mar 2015

Why is cross-origin resource sharing important? That means you can build your web services based on somebody else’s services and contents, instead of rolling out everything on your own. When combined with AJAX, the synergy opens up a more convenient and interactive way for web services to communicate with each other. However, AJAX is confined by a wall called Same Origin Policy because the underlining XMLHttpRequest object is required to follow. Luckily, there are ways to get around it; here I noted down two approaches, CORS and JSONP:

CORS is a mechanism/protocol to allow resources being shared/requested from another domain outside the domain from which the resource originated.

The idea of CORS is pretty simple: if CORS is enabled on the server-side, the response sent by the server will contain some HTTP headers like, Access-Control-Allow-Origin, and then it is generally the browser’s responsibility to support the headers and respect the restrictions they impose. Wonder which browers support CORS? Check out Can I use CORS. Basically many modern browsers already support CORS.

Since CORS is only enabled on the server-side, if you are only a client sending the requests to the server, you can’t do much to make CORS works except making sure your brower is modern enough to respect CORS protocol. In other words, for APIs or servers that support CORS, you can just use it; for those that do not, you will need to do it in other ways, for example, JSONP.

JSONP takes the advantage that Same-Origin Policy is not imposed on <script> tags. When a server is ‘JSONP enabled’, it will take a callback function you pass in as a parameter in the request, and return the data wrapped with that callback function as a response and injected as a script into your page. In other words, it is basically a cross-domain javascript injection. To better understand it, here is a demo and examples. To use JSONP, the server or API needs to enable that feature for it to work. You need to read API’s documentation to know if JSONP is supported.

Some real world examples: New York Times Article Search API v2 supports CORS (you will realize that once you check the HTTP response headers returned by the API service); and Wikipedia API supports JSONP.

From my point of view, CORS is a much ‘proper’,structural solution but it is newer so the backward compatibility is not that good. JSONP is more like a hack and has more security concerns but it is supported even by older browers.