Recently, I’ve been working on an HTML5 project that needed to need to retrieve data from a different origin, and decided to look at using CORS.
CORS, or Cross-Origin Resource Sharing is a specification that allows web applications to make AJAX calls cross-origin without resorting to workarounds such as JSONP.
Searching around, I found an CORS extension for Sinatra, which happened to be the framework I was using. However, the extension didn’t properly implement the spec, nor did it support CORS preflighting (required for more complex AJAX requests). So I rolled my own, but as a Rack Middleware. Here’s an example of a Rackup that shows it in action (this example uses Rack::CORS in Sinatra app, but should be able to use it in any Rack compatible framework):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
To get going with Rack::CORS, just install the rack-cors Gem. To check out the source, see the project on Github.
If you want to learn more about CORS, here are some good links I found along the way:
- The W3C Working Draft on CORS, for good night time reading.
- A good article about CORS that summarizes the CORS spec.
- You can check if your browsers support CORS here. This site records all pass/fails so you’ll be able to see a list of CORS supported (and not supported) browsers.
- The Sinatra CORS Extension I found.