Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

ruby - Can't get rack-cors working in rails application

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...