Can't get rack-cors working in rails application

后端 未结 6 1264
野的像风
野的像风 2020-12-12 19:47

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 up

6条回答
  •  我在风中等你
    2020-12-12 20:24

    Here's how I fixed mine:

    You just need to un-comment the Rack CORS gem in your Gemfile (if it's there) or just add it:

    gem 'rack-cors'
    

    And then run the code below to install the gem:

    bundle install
    

    Put the code below in config/application.rb of your Rails application. For example, this will allow GET, POST or OPTIONS requests from any origin on any resource:

    module YourApp
      class Application < Rails::Application
        # ...
    
        # For Rails 5 Appications
    
        config.middleware.insert_before 0, Rack::Cors do
          allow do
            origins '*'
            resource '*', headers: :any, methods: [:get, :post, :options]
          end
        end
    
        # For Rails 3/4 Applications
    
        config.middleware.insert_before 0, "Rack::Cors" do
          allow do
            origins '*'
            resource '*', headers: :any, methods: [:get, :post, :options]
          end
        end
      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.

    Note: If you're running Rails, updating in config/application.rb should be enough. There is no need to update config.ru as well.

    That's all

    I hope this helps.

提交回复
热议问题