【发布时间】:2014-08-20 22:52:09
【问题描述】:
我在http://www.domain_a.com 上有一个网站,我需要向http://domain_b.com 上托管的 JSON API 发出请求。现在,当我尝试以下操作时:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON({
url: "http://domain_b.com/service_api/v1/find.json?name=abcd",
dataType: 'json',
beforeSend: setHeader,
success: function(data) {console.log (data)}
});
function setHeader (xhr) {
console.log (xhr);
xhr.setRequestHeader("Authorization", "sdkfhberg83hr87234bf87r432");
console.log (xhr);
}
});
</script>
</head>
<body>
</body>
</html>
我在 firebug 控制台中收到此错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domain_b/service_api/v1/find.json?name=abcd. This can be fixed by moving the resource to the same domain or enabling CORS.
是我做错了什么,还是根本不允许(会让我感到惊讶)?
【问题讨论】:
-
你要找的是CORS,跨域资源共享,需要在托管API的域上设置。
-
不允许,除非提供 api 的服务器设置标头表明允许