Heroku, Rails 4, and CORS

Tuesday, August 18th 2015

It seems out of no where Heroku changed the way you configure CORS. All of a sudden I couldn't post from my ember app to my rails app. I'd get this error:

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access

Which was baffling to me. I had already set up CORS!... Or so I thought. It used to be you'd install the rack CORS gem and in your Rails application config you'd put your code to configure CORS. Now you have to move that CORS config to config.ru. Here's how it looks now:

  • Put this gem in your gemfile if it isn't already gem 'rack-cors', :require => 'rack/cors'
  • And then in your config.ru file right after run Rails.application:

    require 'rack/cors'
    use Rack::Cors do
    
    # allow all origins in development
    allow do
      origins '*'
      resource '*', 
          :headers => :any, 
          :methods => [:get, :post, :delete, :put, :options]
    end
    end
    

And that should do the trick! You can now configure CORS however you desire :)