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

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

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


当前回答

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

其他回答

正如其他人所说,如果cookie的主机、路径等限制得到满足,它将被发送50次。

但是您还问了为什么:因为cookie是HTTP特性,而HTTP是无状态的。HTTP被设计成无需服务器在请求之间存储任何状态即可工作。

事实上,服务器没有一个可靠的方法来识别哪个用户发送了一个给定的请求;一个web代理(IP地址)背后可能有1000个用户。如果不是每个请求都发送cookie,服务器将无法知道哪个用户正在请求任何资源。

最后,浏览器不知道服务器是否需要cookie,它只知道服务器指示它为任何请求发送cookie到foo.com,所以它这样做了。有时图像需要它们(例如,每个用户动态生成),有时不需要,但浏览器无法分辨。

三年过去了

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.

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

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

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.

是的,只要请求的URL在cookie中定义的相同域和路径(以及所有其他限制——安全、httponly、未过期等)保持,那么cookie将为每个请求发送。