Talking to a cross-domain API (CORS) with Backbone JS and Ruby on Rails

After doing a whole load of reading, the solution is absolutely simple. Here’s what to do. On your backbone (or any other client side JS) side, we add some jQuery goodness with the following method:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
    options.url = ‘http://yourdomain.com’ + options.url;
});

This prefilter allowed all my BackboneJS calls to be hitting the remote API correctly. I’ve put this on my main.js before the router is initialised just to be sure.

The difficult bit was the server support for CORS (cross-origin resource sharing). Browsers don’t like to let webapps just talk to other domains by default and require the server to specifically support this.

With CORS, there’s generally 2 calls made. The first call is a test from the browser with the HTTP header OPTIONS. Browser asks for what HTTP headers, requests and origins are allowed by the server. Your server has to respond accordingly or none of this will work. The next call is the actual backbone fetch() call.

After all that reading… yes, someone made a fantastic gem for this purpose!! Rack-Cors (https://github.com/cyu/rack-cors) is a rack-middleware addon. The setup instructions are there, it works with rails 3. Quick sample below from application.rb. And that’s it!!

config.middleware.use Rack::Cors do
    allow do
      origins 'https://yourdomain', 'localhost:3000'
      resource '*', :headers => :any, :methods => [:get, :post, :options]
    end
  end