CORS问题:获取错误“No”Access-Control-Allow-Origin'header is present“当它实际上是 [英] CORS issue: Getting error "No 'Access-Control-Allow-Origin' header is present" when it actually is
问题描述
我怀疑为我的应用程式提供服务的后端很重要,但如果您关心,我将使用 rack-cors 一个Rails 4.0应用程序。
I doubt the backend serving my app is important, but if you care, I'm using rack-cors with a Rails 4.0 app.
使用jQuery,我发送我的应用程序一个 PATCH
Using jQuery, I send my app a PATCH
request like so:
$.ajax({
url: "http://example.com/whatever",
type: "PATCH",
data: { something: "something else" }
})
当我从Chrome触发此调用时,我看到一个成功的 OPTIONS
请求出去,它从我的服务器返回这些头:
When I trigger this call from Chrome, I see a successful OPTIONS
request go out, which returns these headers from my server:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:accept, content-type
Access-Control-Allow-Methods:GET, PUT, PATCH, OPTIONS
Access-Control-Allow-Origin: http://sending-app.localhost:3000
Access-Control-Expose-Headers:
Access-Control-Max-Age:15
然后我看到 PATCH
请求退出,会抛出此错误:
Then I see a PATCH
request go out, which throws this error:
XMLHttpRequest无法加载 http://example.com/whatever 。在所请求的资源上没有Access-Control-Allow-Origin头。原因 http://sending-app.localhost:3000 因此不允许访问。
XMLHttpRequest cannot load http://example.com/whatever. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sending-app.localhost:3000' is therefore not allowed access.
我已尝试从 PATCH
切换到 PUT
,结果相同。
I have tried switching from PATCH
to PUT
with the same results.
这对我没有任何意义。发生了什么?
This doesn't make any sense to me. What's going on?
我认为标题告诉整个故事,但是由于人们感到困惑,这里是我的 config / application.rb
文件,这是如何配置Rails的rack-cors插件:
I thought the headers told the whole story, but since people are confused, here's my config/application.rb
file, which is how the rack-cors plugin for Rails is configured:
config.middleware.use Rack::Cors do
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :put, :patch, :options],
:max_age => 15
end
end
推荐答案
排除Rails CSRF检查操作;)
Exclude Rails CSRF checking in the action ;)
也就是说,Rails使用update / create请求检查真实性令牌。在您的Rails应用程序中,此令牌将添加到您的所有表单。
That is, Rails checks for an authenticity token with update/create requests. Within your Rails app, this token is added to all of your forms. But with javascript requests, including it is tricky.
您可以通过将此操作添加到您的控制器来跳过检查操作:
You can skip checking it for an action by adding this to your controller:
skip_before_filter :verify_authenticity_token, :only => [:update]
BTW,你的问题与CORS无关,消息在浏览器中。 Rails日志会告诉您真实的故事。
BTW, your problem had nothing to do with CORS, you were getting a bad error message in the browser. The Rails log tells the real story.
这篇关于CORS问题:获取错误“No”Access-Control-Allow-Origin'header is present“当它实际上是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!