javascript - jquery 的 CORS 错误

标签 javascript jquery ajax cors

我目前正在使用 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/

相关文章:

javascript - 修改 Canvas 对象

javascript - 暂停后如何停止加载嵌入的youtube视频

javascript - 使用 qTip 工具提示通过 AJAX 加载数据。 $(this) 不是我期望的那样

jquery - 使用 jQuery.find() 和 XML 文档获取 HTMLUnknownElement

javascript - 如何保留分割定界符 RegExp 两侧的内容?

javascript - 如何在不使控制台崩溃的情况下同时或按顺序缩小/压缩数千个 JS 文件(包括一些大文件)?

jquery - jQuery 中的可编辑下拉菜单

jQuery 没有立即生效

javascript - 为什么我的 Angular 代码似乎正在回发

jquery - 从 MS Office 加载项向第三方服务器发出 AJAX 请求