同源策略:为什么JS代码无法向其域发出HTTP请求?

时间:2020-05-06 17:10:51

标签: javascript security same-origin-policy websecurity

示例

我有一个站点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具有相同的域名(来源)。 相同来源政策是否应该允许它?

1 个答案:

答案 0 :(得分:1)

来源取决于JavaScript加载到的网页的URL,而不是JS文件本身的URL。