为什么浏览器在请求 JavaScript 文件时不发送 cookie?

Why the browser doesn't send cookies while requesting a JavaScript file?

我正在使用 script 标签在 [site2]/page.html 上加载 [site1]/script.js。 并且浏览器在请求 JS 文件时不发送 cookie。

回应headers:

HTTP/1.1 200 OK
Server: nginx
Date: Thu, 02 Apr 2015 14:45:38 GMT
Content-Type: application/javascript
Content-Length: 544
Connection: keep-alive
Content-Location: script.js.php
Vary: negotiate,Accept-Encoding
TCN: choice
Set-Cookie: test_id=551d5612406cd; expires=Sat, 02-Apr-2016 14:45:38 GMT; path=/
Content-Encoding: gzip

请求 headers - 没有 cookie:

GET /script.js HTTP/1.1
Host: [site1]
Connection: keep-alive
Cache-Control: max-age=0
Accept: */*
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: [site2]/page.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: ru,en-US;q=0.8,en;q=0.6,sk;q=0.

浏览器 会在请求 JavaScript 文件时发送 cookie,就像它们在请求其他任何内容时一样。同样的规则适用:cookie 必须用于 origin/path。在您的示例中,您似乎使用了两个不同的来源(site1site2),这可以解释为什么您在请求中看不到 cookie。

例如:我在我的服务器上设置了一个名为 test.php 的页面,该页面设置了一个 cookie。然后它有一个 link 到 test2.html,其中包括 foo.js。这些都在同一路径上(/,在我的示例中,因为我很懒,没有为测试创建子目录)。

在浏览器得到 test.php 的响应 headers 中,我看到

Set-Cookie:test=123

如果我随后单击 test2.html,我会在 headers 的 test2.html 请求中看到:

Cookie:test=123

然后我看到 foo.js 的请求,在该请求中我看到:

Cookie:test=123

对不起,是我的失误。 Google Chrome 阻止了第三方 cookie。

默认浏览器发送带有 JavaScript 文件请求的 cookie。

有一种特殊情况,即使来源相同,也不会发送 cookie:加载 ES6 模块时!

<script type="module" src="some-script.js"></script>

这不会发送 cookie,因此如果您的服务器需要对请求进行身份验证,它可能会失败。

作为 this excellent article points out,您需要通过添加 crossorigin 属性:

<script type="module" crossorigin src="some-script.js"></script>

此行为目前被认为是一个错误(这没有任何意义,对吧?)并且已在所有主流浏览器中得到修复。有关详细信息,请参阅上面的 link。