Can't get rack-cors working in rails applicati

2019-01-21 06:06发布

I wanted to implement CORS in my rails application, so I googled rack-cors gem for it. And I did everything as was said in README, that is updated Gemfile accordingly and updated application.rb like this:

module YourApp
  class Application < Rails::Application

    # ...

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

  end
end

But it didn't work. No matter what I did, in the browser console I kept getting message:
XMLHttpRequest cannot load https://somewebsite.com. Origin http://0.0.0.0:3000 is not allowed by Access-Control-Allow-Origin.

After reading this blogpost and issue on github, I realized that maybe position of rack-cors middleware in the middleware stack matters. So I did as was told in the github issue:

module YourApp
  class Application < Rails::Application

    # ...

    config.middleware.insert 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

  end
end

After that, when I run rake middleware rack-cors is really at the top of the stack.
But It still just simply won't work. I keep getting the same error. Anyone, please help.

5条回答
成全新的幸福
2楼-- · 2019-01-21 06:22

After all it came out that this gem has some issues with heroku, on the local machine it works perfectly fine.

查看更多
聊天终结者
3楼-- · 2019-01-21 06:23

Make sure you added or uncommented gem 'rack-cors' in the Gemfile

查看更多
贪生不怕死
4楼-- · 2019-01-21 06:35

I had to create a special route to handle the options requests, the cors gem didn't do it for me like I expected it to. The route I added to the end of routes.rb was:

  match "*path", :to => proc {|env| [200, {
  'Access-Control-Allow-Origin' => '*',
  'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Credentials' => 'true',
  'Access-Control-Request-Method' => '*',
  'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Content-Type' => 'text/plain'

 }, ["CORS Preflight"]] }, :via => [:options]
查看更多
We Are One
5楼-- · 2019-01-21 06:41

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
查看更多
在下西门庆
6楼-- · 2019-01-21 06:48

There is a new issue thread for the heroku solution

Instead of using

config.middleware.use Rack::Cors do

try

config.middleware.insert_before ActionDispatch::Static, Rack::Cors do

That worked for me.

查看更多
登录 后发表回答