Rails CORS发行AJAX API端点请求



我似乎正在遇到一些问题,从而使请求对API端点。我知道Rails在幕后有一些安全性。我正在使用React-Rails,并在componentDidMount中对API端点进行AJAX调用。我也在标题中传递X-Auth-Token

我的控制台错误:

xmlhttprequest无法加载"/api/end/point ..."对飞行前请求的响应不会传递访问控制检查:在请求的资源上不存在'访问访问权限控制。因此,不允许访问原点" http://localhost:3000"。响应具有HTTP状态代码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。无论如何,重新启动您的服务器。

铁轨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

最新更新