Heroku, Rails 4, and Rack::Cors

corsherokuruby-on-rails-4

I am trying to use Rack::Cors with my Rails 4 application so that I can do a JSON based API.

CORS is in my Gemfile like this:

gem 'rack-cors', :require => 'rack/cors'

I am doing the configuration in my application.rb file like this:

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :debug => true, :logger => Rails.logger do
    allow do
        origins '*'
        resource '/messages*', :headers => :any, :methods => [:post, :options]
    end
end

I am inserting after Rails::Rack::Logger in an attempt to get debugging information.

I am using CURL to test it, here is what I have been running:

curl --verbose --request OPTIONS http://jasonbutzinfo.herokuapp.com/messages.json --header 'Origin: http://www.jasonbutz.info' --header 'Access-Control-Request-Headers: Origin, Accept, Content-Type' --header 'Access-Control-Request-Method: POST'

When I run the rails app on my local machine it works without issue. When I hit the Heroku app this is what I get:

> OPTIONS /messages.json HTTP/1.1
> User-Agent: curl/7.30.0
> Host: jasonbutzinfo.herokuapp.com
> Accept: */*
> Origin: http://www.jasonbutz.info
> Access-Control-Request-Headers: Origin, Accept, Content-Type
> Access-Control-Request-Method: POST
> 
* Empty reply from server
* Connection #0 to host jasonbutzinfo.herokuapp.com left intact
curl: (52) Empty reply from server

I did find this question (Can't get rack-cors working in rails application), but there wasn't any helpful answer provided.

Update 11/13/2013 16:40 EST

I've been trying to do some more debugging with what is going on. I have monkey patched a few of Rack::Cors' methods to see if they are even being called on Heroku. I have also changed where I insert Cors to be at the top of the rack middleware stack.

With my monkey patching I have put puts statements in the initialize, call, and allow methods. The initialize and allow methods are both called. The call method is never called. So it seems there is something that is stopping the request before it gets to the cors middleware.

Best Answer

I ran into the same problem with heroku. I found this blog with the same rack-cors issue.

Just moved the use Rack::Cors to config.ru, redeployed to heroku and it works.

require ::File.expand_path('../config/environment',  __FILE__)
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