我目前正在使用 the cloudapp API 开展一个项目我正在使用 jquery。 这是我的代码:
$.ajax({
headers: { "Accept": "application/json"},
type: 'GET',
url: 'http://cl.ly/2wr4',
crossDomain: true,
success: function(data, textStatus, request){
console.log(data);
}
});
当我运行它时,我在 Firefox 中得到 200 OK 响应和这个错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://cl.ly/2wr4. This can be fixed by moving the resource to the same domain or enabling CORS.
Google Chrome 中的这个错误:
XMLHttpRequest cannot load http://cl.ly/2wr4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
控制台没有任何记录。 请问我该如何解决这个错误?
谢谢。
最佳答案
对于那些较新的编码人员来说,一个重要的注意事项是 http://enable-cors.org/server.html 上的所有内容假设您有一个正在运行的服务器。如果您是新手,就像我原来一样,这些类型的答案无济于事。
如果您刚刚在您的计算机、CodePen 等上编写了一些代码 - 您无法配置它。
服务器端和客户端脚本之间有一个重要区别 - 您的 jquery 在客户端(即用户计算机/浏览器)上运行,因此没有设置 header 之类的东西。
当我设置自己的服务器和我自己的 PHP 文件(PHP 是服务器端的,因此它是在服务器上处理的,而不是浏览器)并且能够开始发出请求时,我终于开始在这个问题上取得进展很好。
为那些被淹没在涉及 "Header set Access-Control-Allow-Origin "*"
答案的答案中的任何人添加这个。当我开始时,它真的让我感到沮丧。
关于javascript - jquery 的 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923796/