Rails CORS issue with Ajax API endpoint Request

前端 未结 1 835
感情败类
感情败类 2021-01-28 07:42

I seem to be running into some issues making a GET request to an API endpoint. I know rails has some security going on behind the scenes. I\'m using React-Rails and in my

相关标签:
1条回答
  • Because your frontend will do requests from any origin (any client), you have to enable CORS from any origin. Try

    # 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
    

    I use this in a rails 5 api application. Before rails 5 add rack-cors gem to your Gemfile. Anyway, restart your server.

    rails 3/4

    # config/application.rb
    module YourApp
      class Application < Rails::Application
    
        config.middleware.insert_before 0, "Rack::Cors" do
          allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :options]
          end
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题