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):
require 'sinatra'
require 'rack/cors'
use Rack::Cors do |config|
config.allow do |allow|
allow.origins '*'
allow.resource '/file/list_all/', :headers => :any
allow.resource '/file/at/*',
:methods => [:get, :post, :put, :delete],
:headers => :any,
:max_age => 0
end
end
get '/file/list_all/' do
#...
end
get '/file/at/*' do
#...
end
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.