Can't get rack-cors working in rails application

笑着哭i 提交于 2019-11-28 16:24:40

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

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.

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]

You just need to un-comment the Rack CORS gem in your Gemfile (gemfile.rb)

# gemfile.rb

gem 'rack-cors'

And then run the code below to install the gem

bundle install

And also ensure that your cors initializer (cors.rb) is set this way # config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Setting origins to '*' should be alright for development, but keep in mind that if you deploy to production you’ll want to change this value to match your front-end’s URI for security reasons.

That's all

I hope this helps.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!