我们正在使用Ruby 2.1.2和Rails 3.2.14。 在我们将网站移至SSL后,我们在浏览器控制台上收到了关于ajax请求的以下错误。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://sitename.com/xxx/xx?id=xx. This can be fixed by moving the resource to the same domain or enabling CORS.
我们已尝试添加
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true
但没有效果。这是ajax代码:
$.ajax({
type: "GET",
data: {id: id},
url: path+id,
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true,
success: function(data) { }
});
还有其他建议吗?
答案 0 :(得分:5)
您必须在服务器端设置标头。不在客户端。最简单的方法是在ApplicationController中使用类似的东西:
after_filter :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
end
答案 1 :(得分:2)
亚历山大的答案是正确的。但是,不建议允许所有域访问您的API(除非它是公开的)See CORS section of OWASP Cheatsheet
Rails 5实施
after_action :set_access_control_headers
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = 'mysite.example.com'
end