【发布时间】:2016-09-12 07:29:01
【问题描述】:
我正在尝试在我的 rails 应用中实现 google places api。
这是我在尝试使用从 ajax 请求中获取数据的函数时遇到的错误:
XMLHttpRequest cannot load . 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.
我正在使用 rack-cors gem,并将这个 sn-p 添加到我的 config/application.rb 文件中:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
这是我认为的 ajax 请求(coffeescript):
$.ajax
url: url
dataType: "json"
type: "GET"
我已将此部分添加到我的 application_controller
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, 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, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = '*'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
这个,到我的路线文件
match '*path' => 'application#cors_preflight_check', :via => :options
我注意到“cors_preflight_check”方法不是由我的请求触发的。 (当我单击视图中的某个链接时,我会发出 AJAX 请求)
我注意到我的请求标头保持不变。
(Access-Control-Allow-Origin 未添加到请求标头中)
jsonp 不是一个选项,因为places api 不支持它
尝试了这些线程中编写的所有内容:
- https://github.com/cyu/rack-cors/issues/33
- Can't get rack-cors working in rails application (config.middleware.insert 0, Rack::Cors do)
- https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html
- POST Method not working in rack-cors rails 4(在应用控制器中添加前后操作)
- Add custom response header with Rack-cors and Grape(使用 :expose 键)
【问题讨论】:
-
你要部署什么?这是您的本地开发设置吗?对于我的部署,我最终不得不在我的例子 nginx 的配置文件中设置服务器设置中的标头。
-
我相信我在使用 Webrick,你能解释一下吗?
标签: ruby-on-rails ajax api cors rack-cors