示例
我有一个站点http://example.com
。此网站使用第三方JS代码:<script src="http://third.party/script.js"></script>
http://third.party/script.js
包含以下代码:
console.log("self.origin", self.origin);
fetch("http://third.party/api");
当我打开http://example.com
时,我在开发控制台中得到以下输出:
self.origin http://example.com
Access to fetch at 'http://third.party/api' from origin 'http://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
第三方脚本尝试从第三方API加载数据,但失败。为什么失败了?
第三方脚本和API具有相同的域名(来源(。同源政策应该允许吗?
来源由JavaScript加载到的网页的URL决定,而不是JS文件本身的URL。