微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 使用jquery的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);
            }
 });

当我运行这个时,我得到200 OK响应并在Firefox中出现此错误

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.

并且没有任何内容记录到控制台.
请问我该如何解决这个错误

谢谢.

解决方法:

CORS(跨源资源共享)是一种HTML5功能,允许一个站点访问另一个站点的资源,尽管它们位于不同的域名下.

CORS的W3C规范实际上提供了一些响应头的简单示例,例如密钥头​​,Access-Control-Allow-Origin以及必须用于在Web服务器上启用CORS的其他头.

如果您正在寻找有关如何在各种常见Web服务器上设置CORS的特定信息,请查看启用CORS共享网站. http://enable-cors.org/

根据您在上面提供的URL,我认为您无法控制该服务器.因此,它根本行不通.

即使您已启用crossDomain:true,服务器也应返回所需的标头,例如:

这是一个有效的服务器响应; CORS特定的标题是粗体

HTTP响应:

Access-Control-Allow-Origin: http://xyzcom
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

你可以尝试的一件事是:

$.ajax({
            headers: { "Accept": "application/json"},
            type: 'GET',
            url: 'http://cl.ly/2wr4',
            crossDomain: true,
            beforeSend: function(xhr){
                xhr.withCredentials = true;
          },
            success: function(data, textStatus, request){
                console.log(data);
            }
 });

否则,您需要联系API提供商.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐