每个网络请求都会发送浏览器的cookie吗?

我说的不是页面浏览量,而是对图像、.js文件等的请求。

更新 如果一个网页有50个元素,那就是50个请求。为什么它会为每个请求发送相同的cookie(s),它不是缓存或知道它已经有了它吗?


当前回答

简短的回答是肯定的。下面的代码行来自JS文档

cookie曾经被用于一般的客户端存储。虽然当它们是在客户端上存储数据的唯一方式时,这是合法的,但现在建议使用现代存储api。cookie随每个请求一起发送,因此它们会降低性能(特别是对于移动数据连接)。

其他回答

三年过去了

There's another reason why a browser wouldn't send cookies. You can add a crossOrigin attribute to your <script> tag, and the value to "anonymous". This will prevent cookies to be sent to the destination server. 99.9% of the time, your javascripts are static files, and you don't generate that js code based on the request's cookies. If you have 1KB of cookies, and you have 200 resources on your page, then your user is uploading 200KB, and that might take some time on 3G and have zero effect on the result page. Visit HTML attribute: crossorigin for reference.

Cookie有一个“path”属性。如果“path=/”,答案是Yes。

是的。每个请求都发送属于同一个域的cookie。它们不是缓存的,因为HTTP是无状态的,这意味着每个请求都必须足够让服务器知道如何处理它。假设你的图片只能被特定的用户访问;你必须在这50个请求中每一个都发送你的身份验证cookie,这样服务器就知道它收到的请求池中是你而不是其他人或客人。

Having said that, cookies might not be sent given other restrictions mentioned in the other responses, such as HTTPS setting, path or domain. Especially there, an important thing to notice: cookies are not shared between domains. That helps with reducing the size of HTTP calls for static files, such as the images and scripts you mentioned. Example: you have 4 cookies at www.stackoverflow.com; if you make a request to www.stackoverflow.com/images/logo.png, all those 4 cookies will be sent. However, if you request stackoverflow.com/images/logo.png (notice the subdomain change) or images.stackoverflow.com/logo.png, those 4 cookies won't be present - but maybe those related to these domains will.

您可以阅读更多关于cookie和图像请求,例如,在这篇StackOverflow博客文章。

I know this is an old thread. But I've just noticed that most browsers won't sent cookies for a domain if you add a trailing dot. For example http://example.com. won't receive cookies set for .example.com. Apache on the other hand treats them as the same host. I find this useful to make cross domain tracking more difficult for external resources I include, but you could also use it for performance reasons. Note this brakes validation of https certificates. I've run a few tests using browsershots and my own devices. The hack works on almost all browsers except for safari (mobile and desktop), which will include cookies in the request.

简短的回答是肯定的。下面的代码行来自JS文档

cookie曾经被用于一般的客户端存储。虽然当它们是在客户端上存储数据的唯一方式时,这是合法的,但现在建议使用现代存储api。cookie随每个请求一起发送,因此它们会降低性能(特别是对于移动数据连接)。