Rails: 在哪里启用 Access-Control-Allow-Origin

Rails: where to enable Access-Control-Allow-Origin

我正在尝试在我的 coffeescript 文件中加载 link,如下所示:

$.ajax hobby.link,
  type: 'GET'
  dataType: 'html'
  error: (jqXHR, textStatus, errorThrown) ->
    console.log "AJAX Error"
  success: (data, textStatus, jqXHR) ->
    console.log "Successful AJAX call"

并已安装

gem 'rack-cors', :require => 'rack/cors'

并添加了

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

到我的application.rb,但每次我得到

XMLHttpRequest cannot load http://www.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我还需要做什么才能使这些负载工作?

请注意,我目前正在连续执行对三个不同 link 的 ajax 调用。

错误代码表明您尝试加载的第 3 方网站不允许来自其域外的请求。这不是您的应用程序的问题,他们不允许不是来自他们自己的域的请求。

这是对解释 CORS 工作原理的 CSRF attacks. See this 答案的衡量。

Rack::Cors 处理允许或拒绝 您自己的 网站和域的 CORS。它不会影响任何其他域的 CORS 配置。

例如,您的网站可能是 http://example.com,而您正在尝试向 http://example.net 发送 AJAX 请求。由于 example.net 不受您的控制,因此您无法控制其 CORS 设置,Rack::Cors 也无法控制。这意味着如果 example.net 不允许 AJAX 请求,您将无能为力。

与您尝试调用的服务的管理员交谈,看看是否可以说服他们允许 AJAX 请求(至少来自您的域)。