每个网络请求都会发送浏览器的cookie吗?
我说的不是页面浏览量,而是对图像、.js文件等的请求。
更新 如果一个网页有50个元素,那就是50个请求。为什么它会为每个请求发送相同的cookie(s),它不是缓存或知道它已经有了它吗?
每个网络请求都会发送浏览器的cookie吗?
我说的不是页面浏览量,而是对图像、.js文件等的请求。
更新 如果一个网页有50个元素,那就是50个请求。为什么它会为每个请求发送相同的cookie(s),它不是缓存或知道它已经有了它吗?
当前回答
是的,只要请求的URL在cookie中定义的相同域和路径(以及所有其他限制——安全、httponly、未过期等)保持,那么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.
三年过去了
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。它们不是缓存的,因为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博客文章。
是的,只要请求的URL在cookie中定义的相同域和路径(以及所有其他限制——安全、httponly、未过期等)保持,那么cookie将为每个请求发送。
正如其他人所说,如果cookie的主机、路径等限制得到满足,它将被发送50次。
但是您还问了为什么:因为cookie是HTTP特性,而HTTP是无状态的。HTTP被设计成无需服务器在请求之间存储任何状态即可工作。
事实上,服务器没有一个可靠的方法来识别哪个用户发送了一个给定的请求;一个web代理(IP地址)背后可能有1000个用户。如果不是每个请求都发送cookie,服务器将无法知道哪个用户正在请求任何资源。
最后,浏览器不知道服务器是否需要cookie,它只知道服务器指示它为任何请求发送cookie到foo.com,所以它这样做了。有时图像需要它们(例如,每个用户动态生成),有时不需要,但浏览器无法分辨。