【问题标题】:Same Origin Policy: Why can't JS code make an HTTP request to its domain?同源策略:为什么 JS 代码不能向其域发出 HTTP 请求?
【发布时间】:2020-08-21 18:20:33
【问题描述】:

示例

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

【问题讨论】:

  • 消息非常清楚:“从源 'example.com' 获取在 'third.party/api' 的访问权限” 所以它的源不同。即使从第三方来源加载 JS 也可以被操纵,因此假设这一点并不总是安全的。如果您控制该第三方域,请添加一条规则以接受您的来源,否则,该 api 应该有一个用于该目的的 jsonp api 端点。

标签: javascript security same-origin-policy websecurity


【解决方案1】:

来源是由加载 JavaScript 的网页的 URL 确定的,而不是 JS 文件本身的 URL。

【讨论】:

    猜你喜欢
    • 2012-12-25
    • 2021-02-22
    • 1970-01-01
    • 2016-01-30
    • 2011-06-22
    • 2013-11-28
    • 2016-12-04
    • 2018-10-02
    • 2014-12-26
    相关资源
    最近更新 更多