如何处理多个同名的cookies? [英] How to handle multiple cookies with the same name?

查看:31
本文介绍了如何处理多个同名的cookies?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个应用程序发送以下 HTTP 标头以设置为名为a"的 cookie:

Say for example I had an application sending the following HTTP headers to set to cookie named "a":

Set-Cookie: a=1;Path=/;Version=1
Set-Cookie: a=2;Path=/example;Version=1

如果我在服务器上访问 /example 两个路径都是有效的,所以我有两个名为a"的 cookie!由于浏览器不发送任何路径信息,因此无法区分这两个 cookie.

If I access /example on the server both paths are valid, so I have two cookies named "a"! Since the browser doesn't send any path information, the two cookies cannot be distinguished.

Cookie: a=2; a=1

这种情况应该如何处理?选第一个?创建一个包含所有 cookie 值的列表?还是应该将这种情况视为开发人员的错误?

How should this case be handled? Pick the first one? Create a list with all cookie values? Or should such a case be considered as a developer's mistake?

推荐答案

来自 SitePoint 上的这篇文章:

如果多个同名 cookie 与给定的请求 URI 匹配,则浏览器会选择一个.

If multiple cookies of the same name match a given request URI, one is chosen by the browser.

路径越具体,优先级越高.然而,基于其他属性(包括域)的优先级未指定,并且可能因浏览器而异.这意味着,如果您针对.example.org"和www.example.org"设置了同名 cookie,您就无法确定会发回哪一个.

The more specific the path, the higher the precedence. However precedence based on other attributes, including the domain, is unspecified, and may vary between browsers. This means that if you have set cookies of the same name against ".example.org" and "www.example.org", you can’t be sure which one will be sent back.

这个 2010 年的信息似乎已经过时,浏览器现在似乎可以发送多个 cookie 作为回报,详情请参阅下面@Nate 的回答

this information from 2010 appears to be outdated, it seems browsers can now send multiple cookies in return, see answer by @Nate below for details

这篇关于如何处理多个同名的cookies?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆