更新时间:2023-11-27 22:00:22
Cookie是网站用于在浏览器上存储状态信息的键/值对。
假设您有一个网站(example.com),当浏览器请求网页时,网站可以发送Cookie以在浏览器上存储信息。
浏览器请求示例:
GET /index.html HTTP / 1.1
主机:www.example.com
服务器回答示例:
HTTP / 1.1 200 OK
Content-type:text / html
Set-Cookie:foo = 10
Set-Cookie:bar = 20; Expires = Fri,30 Sep 2011 11:48:00 GMT
...响应的其余部分
这里,两个cookie foo = 10和bar = 20存储在浏览器中。第二个将于9月30日到期。
GET /spec.html HTTP /
在每个后续请求中,浏览器会将Cookie发送回服务器。 1.1
主机:www.example.com
Cookie:foo = 10; bar = 20
接受:* / *
服务器端Cookie被称为会话。在这种情况下,网站在浏览器上存储一个cookie,其中包含唯一的会话标识符。状态信息(上面的foo = 10和bar = 20)存储在服务器上,会话标识符用于将请求与存储在服务器上的数据进行匹配。
您可以使用会话和cookie存储:身份验证数据,用户首选项,电子商务网站中的图表内容等...
下面的解决方案的利弊。
Cookie优点:
Cookie缺点:
会话优惠:
$ b
会话缺点:
What is the difference between server side cookie and client side cookie? Can you please explain with examples.
Cookies are key/value pairs used by websites to store state informations on the browser. Say you have a website (example.com), when the browser requests a webpage the website can send cookies to store informations on the browser.
Browser request example:
GET /index.html HTTP/1.1
Host: www.example.com
Example answer from the server:
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: foo=10
Set-Cookie: bar=20; Expires=Fri, 30 Sep 2011 11:48:00 GMT
... rest of the response
Here two cookies foo=10 and bar=20 are stored on the browser. The second one will expire on 30 September. In each subsequent request the browser will send the cookies back to the server.
GET /spec.html HTTP/1.1
Host: www.example.com
Cookie: foo=10; bar=20
Accept: */*
Server side cookies are known as "sessions". The website in this case stores a single cookie on the browser containing a unique Session Identifier. Status information (foo=10 and bar=20 above) are stored on the server and the Session Identifier is used to match the request with the data stored on the server.
You can use both sessions and cookies to store: authentication data, user preferences, the content of a chart in an e-commerce website, etc...
Below pros and cons of the solutions. These are the first that comes to my mind, there are surely others.
Cookie Pros:
Cookie Cons:
Session Pros:
Session Cons: