Ajax API端点请求的Rails CORS问题 [英] Rails CORS issue with Ajax API endpoint Request
问题描述
我似乎在向API端点发出GET请求时遇到了一些问题.我知道Rails在幕后有一些安全措施.我正在使用React-Rails并在我的componentDidMount
中对API端点进行ajax调用.我也在标题中输入了X-Auth-Token
.
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 componentDidMount
to make an ajax call to an API endpoint. I am passing in a X-Auth-Token
in my headers too.
我的控制台错误:
XMLHttpRequest无法加载"/api/end/point ..."对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:3000 .响应的HTTP状态码为401.
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呼叫看起来像
My ajax call is looking like
$.ajax({ url: "my/api/endpoint...", headers: {"X-Auth-Token": "My API token..."},
success: (response) => { console.log(response); } })
推荐答案
由于您的前端将发出来自任何来源(任何客户端)的请求,因此您必须启用来自任何来源的CORS.试试
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
我在Rails 5 API应用程序中使用它.在rails 5之前,将rack-cors
gem添加到您的Gemfile
中.无论如何,请重新启动服务器.
I use this in a rails 5 api application. Before rails 5 add rack-cors
gem to your Gemfile
. Anyway, restart your server.
导轨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
这篇关于Ajax API端点请求的Rails CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!