【发布时间】:2014-01-16 03:18:27
【问题描述】:
我正在使用 Rails 4 创建一组服务,我在 JavaScript 浏览器应用程序中使用这些服务。跨域 GETS 工作正常,但我的 POST 未通过预检 OPTIONS 检查并出现 404 错误。至少,我认为这就是正在发生的事情。以下是控制台中出现的错误。这是 Mac 上的 Chrome 31.0.1650.63。
OPTIONS http://localhost:3000/confessor_requests 404 (Not Found) jquery-1.10.2.js:8706
OPTIONS http://localhost:3000/confessor_requests No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. jquery-1.10.2.js:8706
XMLHttpRequest cannot load http://localhost:3000/confessor_requests. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. main.html:1
我搜索了有关启用 CORS 的说明,但我很困惑。通常的建议似乎是在 Application 控制器中放置这样的东西,我这样做了。
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == :options
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
随后是 routes.rb 中的某种路由,当 OPTIONS 请求进来时,该路由将重定向到此操作。
match "/*all" => "application#cors_preflight_check", :constraints => { :method => "OPTIONS" }
'match' 指令在 Rails 4 中不再有效,所以我摆弄它,试图让它直接匹配 POSTS,如下所示:
post "/*all" => "application#cors_preflight_check", :constraints => { :method => :options }
但它仍然不起作用。由于 GET 请求正在工作,我假设我缺少的是 OPTIONS 请求的正确路由。但是,我已经尝试了所有我能想到的路线,但似乎没有任何东西可以让请求通过。
我也尝试安装cyu/rack-cors,结果相同。
有人知道我做错了什么吗?
【问题讨论】:
-
match应该仍然可以工作,但是如果您没有通过via选项,它会抱怨。用post做这件事绝对行不通。作为之前在rack-cors上犯过这个错误的人,我还要问:您在配置rack-cors中间件后是否重新启动了服务器?我花了一个多小时自己追赶那段时间。 :) -
这里也一样。我已经尝试了自定义方法和 gem:在引发
ActiveRecord::RecordNotFound异常之前一切正常。在这种情况下,CORS 不起作用。 -
我已经进一步调查了这个问题:在我的情况下,预检响应标头是正确的,而实际请求(引发异常时)会产生没有 CORS 标头的响应
标签: ruby-on-rails-4 xmlhttprequest cors rails-routing http-method