ajax跨域请求(cors实现),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请求)

我注意到我的请求 Headers 保持不变 .

(Access-Control-Allow-Origin未添加到请求标头中)

jsonp不是一个选项,因为它不支持places api

尝试了在这些主题中写的所有内容:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值