How to enable CORS in Rails 4 App

后端 未结 3 1421
说谎
说谎 2020-12-09 03:11

I\'m just about to pull my hair out... I\'ve been trying to enable CORS in this Rails app since the morning and it just doesn\'t work. I\'ve tried this, using Rack Cors Gem

相关标签:
3条回答
  • 2020-12-09 03:38

    You should use rack cors

    It provides a nice DSL, to use in your config/application.rb, instead of the messy header work and before filters.

    A very permissive would be as follows, but of course, you'll have to tailor it a bit.

    use Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: :any
      end  
    end
    
    0 讨论(0)
  • 2020-12-09 03:44

    Rack::Cors provides support for Cross-Origin Resource Sharing

    Steps to enable rackcors :

    1.add gem to your Gemfile:

    gem 'rack-cors'
    

    2.Add below code to config/application.rb

    # if you are using Rails 3/4
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => :any
      end
    end
    # if you are using Rails 5
    
    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: :any
      end
    end
    
    0 讨论(0)
  • 2020-12-09 03:49

    Here's what worked for me:

    1. Add this to Gemfile: gem 'rack-cors' then bundle install

    2. Create a new file /config/initializers/cors.rb

    3. Inside the file place the following:

    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: [:get, :post, :patch, :put]
      end
    end
    

    That's it!

    FYI the instructions came directly from here

    0 讨论(0)
提交回复
热议问题