May 30, 2021 Article blog
A cookie is a small piece of text information that the server holds in a browser and cannot be larger than 4KB in general. This information is automatically attached to the browser every time it makes a request to the server.
Cookies primarily hold status information, and here are some of the main uses.
Cookies are not an ideal client storage mechanism. I t has a small capacity (4KB), lacks a data manipulation interface, and can affect performance. C lient storage should use the Web storage API and IndexedDB. Only information that needs to be made known to the server for each request should be placed in a cookie.
For an introduction to Web storage, read this blog: Use of sessionStorage and localStorage
Each cookie has metadata in the following areas.
For example, when a user visits a URL
www.example.com
the server writes a cookie in the browser.
The domain name to which this cookie belongs is
www.example.com
and the effective path is the root path
/
.
If the active path of a cookie is set to
/user
the cookie is only valid if access
www.example.com/use
r and its subpaths.
Later, before the browser accesses a path, it finds cookies that are valid for the domain name and path and have not expired and are sent to the server together.
Users can set that the browser does not accept cookies, or they can set that cookies are not sent to the server. The window.navigator.cookieEnabled property returns a Boolean value indicating whether the browser has cookies turned on.
window.navigator.cookieEnabled // true
document.cookie
property returns the cookie for the current page.
The limits on the number and size of cookies vary from browser to browser. I n general, a single domain name should not set more than 30 cookies, each cookie size can not exceed 4KB. When the limit is exceeded, cookies are ignored and not set.
Two URLs can share cookies as long as they have the same domain name. N
ote that the protocol is not required to be the same here.
That is, cookies set
http://example.com
can be read by
https://example.com
Cookies are generated by the HTTP protocol and are primarily intended for use by the HTTP protocol.
If the server wants to save cookies in a browser, place a
Set-Cookie
field in the header information of the HTTP response.
Set-Cookie:foo=bar
The above code saves a cookie named foo in the browser with a value of bar.
AN HTTP RESPONSE CAN CONTAIN MULTIPLE
Set-Cookie
FIELDS, I.E. GENERATE MULTIPLE COOKIES IN THE BROWSER.
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
In addition to the value of the cookie, the Set-cookie field can attach the properties of the cookie.
Inside a Set-cookie field, multiple properties can be included at the same time, with no order requirements.
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit>
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; Secure
Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly
When the browser sends an HTTP request to the server, each request is brought with a cookie. T
hat is, save this information from the browser earlier and send it back to the server.
The
Cookie
field for HTTP header information is used at this time.
// 会向服务器发送名为 foo的 Cookie,值为 bar。
Cookie: foo=bar
// Cookie字段可以包含多个 Cookie,使用分号(;)分隔。
Cookie: name=value; name2=value2; name3=value3
Here's an example.
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
Expires
property specifies a specific expiration time, after which the browser no longer retains the cookie.
Its value is in UTC format, which can be
Date.prototype.toUTCString()
If the property is not set, or if it is set to null, the cookie is valid only in the current session, and once the browser window is closed and the current session ends, the cookie is deleted. In addition, the browser determines whether a cookie has expired based on local time, and since the local time is inaccurate, there is no guarantee that the cookie will expire at the time specified by the server.
Max-Age
property specifies the number of seconds that cookies exist from now on,
such as 60 x 60 x 24 x 365 (i.e. one year).
After this time, the browser will no longer retain this cookie.
If both
Expires
and
Max-Age
are specified, the values of
Max-Age
take precedence.
If
Set-Cookie
field does not specify
Expires
or
Max-Age
attribute, the cookie is the Session cookie, i.e. it exists only in this conversation and will no longer be retained by the browser once the user closes the browser.
Use Node to create a server to simulate the demo:
const http = require('http')
const fs = require('fs')
http.createServer(function (request, response) {
console.log('request come', request.url)
const html = fs.readFileSync('test.html', 'utf8')
response.writeHead(200, {
'Content-Type': 'text/html',
'Set-Cookie': ['id=123;max-age=2', 'abc=456;HttpOnly']
})
response.end(html)
}).listen(8888)
console.log('http://127.0.0.1:8888')
Domain
property specifies which domain names to include this cookie when a browser makes an HTTP request.
example.com
does not set the domain property of a cookie, the sub.example.com will not be included with the cookie.
Path
property specifies which paths to include this cookie when a browser makes an HTTP request. A
s soon as the browser discovers that the Path property is the first part of the HTTP request path, the cookie is included in the header information. F
or example, if the PATH property is
/
, the request
/docs
path will also contain the cookie.
Of course, the premise is that the domain names must be consistent.
Secure
property specifies that the browser can send the cookie to the server only under the encryption protocol HTTPS. O
n the other hand, if the current protocol is HTTP, the browser automatically ignores the Secure property from the server. T
he property is just a switch and does not need to specify a value.
If the communication is httpS protocol, the switch opens automatically.
HttpOnly
property specifies that the cookie is not available through JavaScript scripts, primarily
document.cookie
property,
XMLHttpRequest
object, and the
Request API
T
his prevents the cookie from being read by the script and will only be brought with it if the browser makes an HTTP request.
For security reasons.
document.cookie
property is used to read and write cookies on the current page.
When read, it returns all cookies on the current page, provided that the cookie does not have HTTPOnly properties.
document.cookie // "foo=bar;baz=bar"
The above code reads out two cookies at once from
document.cookie
which are separated by semicolons. Y
ou must restore manually to remove the value of each cookie.
This is where cookie access data is inconvenient, it does not have perfect access to the data api let us use, we must manually extract their own data.
document.cookie
property is writeable and can be used to add cookies to the current website. A
t the time of writing, the value of the cookie must be written in the form of
key=value
N
ote that there can be no spaces on either side of the equal sign.
document.cookie
can only be written one cookie at a time, and writes are not overwritten, but added.
document.cookie = 'fontSize=14';
// 最终只会有 test1=456 被写进去
document.cookie = 'test1=456;hahah=123'
Differences in the reading and writing behavior of
document.cookie
(all cookies can be read at once, but only one cookie can be written) are related to the cookie communication format of the HTTP protocol.
Set-Cookie
field is a line setting a cookie.
The only way to delete an existing cookie is to set its
expires
property to a past date.
document.cookie = 'fontSize=;expires=Thu, 01-Jan-1970 00:00:01 GMT';