Rails跨域ajax获取请求(CORS)

我正在尝试在我的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,我已将此片段添加到我的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
  • 无法让rails-cors在rails应用程序中工作 (config.middleware.insert 0,Rack :: Cors)
  • https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html
  • POST方法无法在rack-cors rails 4中工作 (在app控制器中添加操作之前和之后)
  • 使用Rack-cors和Grape添加自定义响应标头 (使用:expose键)

我正在尝试在我的rails应用程序中实现google places api。

你似乎对CORS的作用感到困惑。 如果您尝试执行ajax调用,例如https://maps.googleapis.com ,唯一重要的是Google在响应中发送的CORS标头。 如果这不起作用,您可能会尝试使用过时的api版本端点。

请按照以下步骤操作: https : //developers.google.com/maps/documentation/javascript/examples/place-search

如果您希望应用程序能够向其他域提供数据,那么您将提供CORS标头。 但这不太可能导致您的问题,除非您正在执行由单独的前端消耗的Rails api应用程序。

请参阅使用CORS获取有关CORS如何工作的教程。

另一方面, CSP(内容安全策略)允许您为跨域请求设置更宽松的规则。 但在这种情况下不应该需要,因为Google为其Web服务提供了CORS标头。