我目前正在使用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,服务器也应返回所需的标头,例如:
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提供商.