How to – cross domain ajax to a Ruby app


In some cases, you might have a bunch of apps running on different domains/subdomains and/or ports and you would like to make ajax requests between these services. The problem is that browsers wouldn’t let you make such requests because of the Same Origin Policy which only allowed them to make request to resources within the same domain.

However, most browsers (IE 8+, Firefox 3.5+, Safari 4+, Chrome) implement a simple way to allow cross domain requests as defined in this w3C document.

Of course, if your users have an old version of their browser, you  might have to look into jsonp or something else such as cheating by using iframes & setting document.domain. Let’s pretend for a minute that 100% of your users are on Chrome. The only thing you need to do is set a response header listing the accepted domains or “*” for all. A simple Rack middleware to do that would look like that.

 

class XOriginEnabler
  ORIGIN_HEADER = "Access-Control-Allow-Origin"
 
  def initialize(app, accepted_domain="*")
    @app = app
    @accepted_domain = accepted_domain
  end
 
  def call(env)
    status, header, body = @app.call(env)
    header[ORIGIN_HEADER] = @accepted_domain
    [status, header, body]
  end
end

And to use the middleware you would need to set it for use:

use XOriginEnabler

To enable all requests from whatever origin, or pass the white listed domain(s) as shown below.

use XOriginEnabler, "demo.mysite.com demo.mysite.fr demo.techcrunch.com"

For a full featured middleware, see this project.


Similar Posts

  1. #1 by Alfred Rowe - September 14th, 2011 at 16:23

    This is awesome, thanks for the tip.

  2. #2 by Derek Harmel - September 14th, 2011 at 16:42

    I needed to do this myself just the other day and found the rack-cors gem to be very helpful.

  3. #3 by Alex Mankuta - September 15th, 2011 at 04:18

    You may be interested in rack-cors gem. Also you may want to use github version because gem version is a bit behind spec (and — what’s more important — browser implementation of spec).

    • #4 by Matt Aimonetti - September 15th, 2011 at 10:50

      Thanks Alex, the gem is mentioned at the bottom of the post.

  4. #5 by Michael - September 15th, 2011 at 10:47

    This is also necessary to get custom fonts to work in Firefox when pulling fonts from a different domain (like a CDN). I will be writing about it on my blog (missingfeature.com)

  5. #6 by Benjamin Lewis - September 22nd, 2011 at 05:53

    Thanks for the post.

    I’ve been working on some javascript that uses CORS to interact with a RESTful rails app.

    I was getting very excited about it, until i found out that that Safari doesn’t seem to support cookies as defined in the spec. Not sure if it’s a bug or a security feature.

    http://stackoverflow.com/questions/3814375/cross-domain-cookie-using-cors-in-safari

    Does this gem allow safari to pass cookies?

  1. No trackbacks yet.

Comments are closed.