Mashup Standards Part 2: Cross-Origin Resource Sharing (CORS)

In my previous post, I was talking about the JSON-P standard for mashups. It's very handy, but more of a "convention" than a true standard... Nevertheless, it's very popular, including support in jQuery and Twitter. In this post I'm going to discuss what some consider to be the modern alternative to JSON-P: Cross-Origin Resource Sharing, or CORS for short.

Lets say you had two applications, running at app1.example.com and app2.example.com. They both support AJAX requests, but of course, they are limited to the "Same-Origin Policy." This means app1 can make AJAX requests to app1, but not to app2. Let's further assume that you'd like to make a mashup of these two app at mashup.example.com.

No problem! In order to enable cross-origin AJAX, you simply need to make sure app1 and app2 send back AJAX requests with this HTTP header:

Access-Control-Allow-Origin: http://mashup.example.com

This is easily done, by adding one line to the Apache httpd.conf file on app1 and app2:

Header set Access-Control-Allow-Origin http://mashup.example.com

DONE! Now, with standard AJAX calls you can host a HTML page on mashup.example.com and connect to app1> and app2 using nothing but JavaScript! There are about a half dozen additional Cross-origin HTTP header that you can set... including what methods are allowed (GET/POST), how long to cache the data, and how to deal with credentials in the request... naturally, not all browsers support all headers, so your mileage may vary!

Not to mention, because the XmlHttpObject is used, CORS has much better error handling than JSON-P. If there's an error accessing a file, you can catch that error, and warn the end user. Contract that with JSON-P, where there's no built-in way to know when you can't access a file. You can build your own error handling, but there's no standard.

Nevertheless, I still prefer JSON-P for mashups. Why? Well, it boils down to two things: performance, and security. I'll be covering the specifics in part 3 of this port.

Recent comments