可以通过 HTTP GET 请求设置 cookie 吗?
这可能有点道德问题,但我在办公室里就以下问题进行了相当多的讨论:
可以使用 HTTP GET 请求设置 cookie 吗?因为只要 HTTP 请求更改应用程序中的某些内容,您就应该使用 POST 请求。 HTTP GET 只能用于检索由 Request-URI 标识的数据。
在这种情况下,应用程序不会更改,但由于 cookie 已更改,因此当页面再次加载时用户可能会获得不同的体验,这意味着 HTTP GET 请求更改了应用程序行为(但服务器端没有任何更改)。
讨论开始是因为我们想要使用用于设置 cookie 的普通锚元素。
This might be a bit of an ethical question, but I'm having quite a discussion in the office about the following issue:
Is it okay to set a cookie with a HTTP GET request? Because whenever a HTTP request changes something in the application, you should use a POST request. HTTP GET should only be used to retrieve data identified by the Request-URI.
In this case, the application doesn't change, but because the cookie is altered, the user might get a different experience when the page loads again, meaning that the HTTP GET request changed the application behaviour (nothing changed server-side though).
The discussion started because we want to use a normal anchor element to set a cookie.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GET 的问题是,特别是当它们位于 a 标签上时,它们会被 Google 等网站抓取。
就您而言,您不必要地创建很可能永远不会被使用的 cookie。
我还认为 GET 规则实际上并不是关于更改应用程序,更多的是关于更改数据。我很欣赏 cookie 的微妙区别(即您不会更改系统上的数据),但一般来说,这是一个很好的规则,并且无论数据存储在何处,GET 都不应该真正用于更改它。
The problem with GETs, especially if they are on an a tag, is when they get spidered by the likes of Google.
In your case, you'd needlessly be creating cookies that will, more than likely, never get used.
I'd also argue that the GET rule it's not really about changing the application, more about changing data. I appreciate the subtle distinction with the cookie ( i.e. you are not changing data on YOUR system ), but generally, it's a good rule to have, and irrespective of where the data is stored, GET shouldn't really be used to change it.
当用户发出另一个 GET 请求时,他总是可以有不同的体验 - 您不希望为(想象的)时间服务返回相同的数据集:“GET /time/current”。
另外,并不是说您不允许更改服务器端状态来响应 GET 请求 - 例如,增加页面点击计数器是完全“合法”的,即使您将其存储在数据库中。
请考虑9.1.1 安全方法部分
另外,我想说,更改或设置 cookie 来响应 GET 请求是完全可以接受的,因为您只需返回一些数据。
The user can always have different experience when he issues another GET request - you do not expect to return always the same set of data for (imagined) time service: "GET /time/current".
Also, it is not said you are not allowed to change server-side state in response for GET requests - it's perfectly 'legal' to increase a page hit counter, for example, even if you store it in the database.
Consider the section 9.1.1 Safe Methods
Also I would say it is perfectly acceptable to change or set a cookie in response for the GET request because you just return some data.