Doug Waltman

Getting CORS Working in Ruby on Rails

My heart sank when I read the console message:

XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.

I knew why my request was being rejected, but I wasn't quite sure how to go about implementing a solution. I found a lot of helpful information out there. Blog after blog all linked around to the same answers, yet no combination of them seemed to work for me. I knew the answer lay with Calvin Yu's Rack CORS gem, but I still kept seeing this error message.


Luckily, Mark Welburn had the same problem. Not only that, but he also had the answer: Warden was sending the request before the rack-cors gem could work it's magic.

I had to dig around a few of the links on Mark's site, but I finally came up with an environment configuration that worked for me:

# Add to application.rb
config.middleware.insert_before Warden::Manager, Rack::Cors do
  allow do
    origins %r{^https?:\/\/[a-z0-9\-]+.yourawesome.domain}:?\d*$}i
    resource '*',
      headers: :any,
      methods: [:get, :put, :create, :delete]

No more x-origin errors for this Rails project.