我正在使用 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 的说明,但我很困惑。通常的建议似乎是将这样的东西放在应用程序控制器中,我这样做了。
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,这给出了相同的结果。
有人知道我在做什么错吗?