Rails Ajax API 端点请求的 CORS 问题

Rails CORS issue with Ajax API endpoint Request

我似乎 运行 遇到一些问题,向 API 端点发出 GET 请求。我知道 rails 在幕后进行一些安全操作。我正在使用 React-Rails 并在我的 componentDidMount 中对 API 端点进行 ajax 调用。我也在我的 headers 中传递 X-Auth-Token

我的控制台错误:

XMLHttpRequest cannot load "/api/end/point..." Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

我的 ajax 通话看起来像

$.ajax({ url: "my/api/endpoint...", headers: {"X-Auth-Token": "My API token..."},
    success: (response) => { console.log(response); } })

因为您的前端将处理来自任何来源(任何客户端)的请求,您必须从任何来源启用 CORS。尝试

# 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

我在 rails 5 api 应用程序中使用它。在 rails 5 之前添加 rack-cors gem 到您的 Gemfile。不管怎样,重启你的服务器。

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