当前位置:网站首页>Introduction and use of cookies
Introduction and use of cookies
2022-06-22 06:59:00 【webchang】
List of articles
One 、 summary
Cookie It's a small piece of text saved in the browser by the server , The general size cannot exceed 4KB. Every time the browser makes a request to the server , This information will be automatically attached .
Cookie Mainly save status information , Here are some of the main uses .
- dialogue (session) management : Save login 、 Shopping cart and other information to be recorded .
- Personalized information : Save user preferences , For example, the font size of a web page 、 Background color and so on .
- Tracking users : Record and analyze user behavior .
Cookie Not an ideal client storage mechanism . Its capacity is very small (4KB), Lack of data operation interface , And it affects performance . Client storage should use Web storage API and IndexedDB. Only the information that the server needs to know every request , That's where it should be Cookie Inside .
About right Web storage Introduction to , You can see this blog :sessionStorage and localStorage Use
Every Cookie There are metadata in the following aspects .
- Cookie Name
- Cookie Value ( The real data is written here )
- Due time ( Beyond this time, it will fail )
- Domain name ( The default is the current domain name )
- The path to take effect ( The default is the current web address )
for instance , The user visits the website www.example.com, The server writes a... In the browser Cookie. This Cookie The domain name of is www.example.com, The effective path is the root path /.
If Cookie The effective path of is set to /user, So this Cookie Only during the visit www.example.com/user And its child paths . in the future , Before the browser accesses a path , It will find out that the domain name and path are valid , And not yet due Cookie, Send it to the server .
Users can set the browser not to accept Cookie, You can also set not to send to the server Cookie. window.navigator.cookieEnabled Property returns a Boolean value , Indicates whether the browser is open Cookie function .
window.navigator.cookieEnabled // true
document.cookie Property to return the current web page Cookie.
Different browser pairs Cookie Limitation of quantity and size , It's different . Generally speaking , Single domain name settings Cookie Should not exceed 20 individual , Every Cookie The size of cannot exceed 4KB. Beyond the limit ,Cookie Will be ignored , Will not be set .
As long as the domain name of the two URLs is the same , You can share Cookie. Be careful , The agreement is not required to be the same here . in other words ,http://example.com Set up Cookie, Can be https://example.com Read .
Two 、Cookie And HTTP agreement
Cookie from HTTP Protocol generation , Mainly for HTTP Agreement to use .
1、HTTP Respond :Cookie Generation
If the server wants to save Cookie, Will be in HTTP In the response header , Place a Set-Cookie Field .
Set-Cookie:foo=bar
The above code will save a file named foo Of Cookie, Its value is bar.
HTTP A response can contain more than one Set-Cookie Field , That is to generate multiple Cookie.
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
except Cookie Value ,Set-Cookie Fields can also be attached with Cookie Properties of . One Set-Cookie In the field , You can include multiple attributes at the same time , There is no order requirement .
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

2、HTTP request :Cookie Sending of
Browser to server HTTP When asked , Each request will be accompanied by a corresponding Cookie. in other words , Save the server in the browser earlier , And send it back to the server . Use at this time HTTP Head message Cookie Field .
// Will send a message named to the server foo Of Cookie, The value is bar.
Cookie: foo=bar
// Cookie Fields can contain more than one Cookie, Use semicolon (;) Separate .
Cookie: name=value; name2=value2; name3=value3
Here is an example .
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry

3、 ... and 、Cookie Properties of
1、Expires,Max-Age
Expires Property specifies a specific expiration time , After the appointed time , The browser doesn't keep this anymore Cookie. Its value is UTC Format , have access to Date.prototype.toUTCString() Format conversion .
If this property is not set , Or set to null,Cookie Only in the current session (session) It works , Once the browser window is closed , End of current session , The Cookie It will be deleted . in addition , Browser based on local time , decision Cookie Is it overdue , Because the local time is not accurate , So there's no way to guarantee Cookie It will expire at the time specified by the server .
Max-Age Property specifies from now on Cookie Seconds of existence , such as 60 * 60 * 24 * 365( One year ). After this time , The browser doesn't keep this anymore Cookie.
If you also specify Expires and Max-Age, that Max-Age The value of will take precedence .
If Set-Cookie Field does not specify Expires or Max-Age attribute , So this Cookie Namely Session Cookie, That is, it only exists in this dialogue , Once the user closes the browser , The browser won't keep this Cookie.
Use Node 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')


2、Domain,Path
Domain Property specifies that the browser issues HTTP When asked , Which domain names should be attached with this Cookie.
- If the property is not specified , The browser will set it as the current domain name by default , At this time, the subdomain name will not be attached with this Cookie. such as ,
example.comNot set up Cookie Of domain attribute , thatsub.example.comWill not come with this Cookie. - If you specify domain attribute , Then the subdomain name will also come with this Cookie. If the domain name specified by the server does not belong to the current domain name , The browser will reject this Cookie.
- One sentence summary :Domain The identity specifies which hosts can accept Cookie. If you don't specify , The default is the current host ( Does not contain subdomains ). If you specify Domain , It usually contains subdomains .
Path Property specifies that the browser issues HTTP When asked , Which paths need this Cookie. As long as the browser finds ,Path The attribute is HTTP The beginning of the request path , I'll take this with me in the header Cookie. such as ,PATH The attribute is /, So request /docs The path will also contain the Cookie. Of course , The premise is that the domain names must be consistent .
3、Secure,HttpOnly
Secure Property specifies that the browser is only in encryption protocol HTTPS Next , To put this Cookie Send to server . On the other hand , If the current agreement is HTTP, The browser will automatically ignore the server sent Secure attribute . This property is just a switch , You do not need to specify a value . If the communication is HTTPS agreement , The switch turns on automatically .
HttpOnly Property specifies the Cookie Unable to get JavaScript The script gets , Mainly document.cookie attribute 、XMLHttpRequest Objects and Request API Can't get the attribute . This prevents the Cookie Read by the script , Only the browser sends HTTP When asked , Will bring the Cookie. For safety reasons .
Four 、document.cookie
document.cookie Property is used to read and write the current web page Cookie. When reading , It will return all of the current web page Cookie, The premise is that Cookie Can not have HTTPOnly attribute .
document.cookie // "foo=bar;baz=bar"
The above code comes from document.cookie Read two at a time Cookie, They are separated by semicolons . You have to restore it manually , To take out every one of them Cookie Value . This is it. cookie Where access to data is inconvenient , It doesn't have a perfect way to access data api Let's use it , We must manually extract the data we need .
document.cookie Properties are writable , It can be used to add... To the current website Cookie. When writing ,Cookie The value of must be written as key=value In the form of . Be careful , There can be no spaces on either side of the equal sign .document.cookie You can only write one at a time Cookie, And writing is not an overlay , But add .
document.cookie = 'fontSize=14';
// In the end, there will only be test1=456 Be written in
document.cookie = 'test1=456;hahah=123'
document.cookie Differences in reading and writing behavior ( You can read all at once Cookie, But only one... Can be written Cookie), And HTTP Agreed Cookie Communication format .
- Browser to server Cookie When ,Cookie The field is to use one line for all Cookie Send it all ;
- The server sets... To the browser Cookie When ,
Set-CookieA field is a line that sets one Cookie.
Delete an existing Cookie The only way , It was set up expires Attribute is a past date .
document.cookie = 'fontSize=;expires=Thu, 01-Jan-1970 00:00:01 GMT';
5、 ... and 、 Reference material
Cookie - JavaScript course - Net channel
Front end learning exchange QQ Group , The atmosphere of learning and discussion in the group is very good , There are a lot of big people , Looking forward to your joining :862748629 Click to add
边栏推荐
- Training penetration range 02 | 3-star VH LLL target | vulnhub range node1
- Convolutional neural network (notes, for personal use)
- Golang appelle sdl2, lit l'audio PCM et signale une erreur lors de l'exécution externe du Code.
- JDBC query result set, which is converted into a table
- Py之scorecardpy:scorecardpy的简介、安装、使用方法之详细攻略
- PIP for source changing and accelerated downloading
- Implement a timer: timer
- Qt development simple Bluetooth debugging assistant (low power Bluetooth)
- Tableau 连接mysql详细教程
- 圣杯布局和双飞翼布局的区别
猜你喜欢
![[meta learning] classic work MAML and reply (Demo understands meta learning mechanism)](/img/e5/ea68e197834ddcfe10a14e631c68d6.jpg)
[meta learning] classic work MAML and reply (Demo understands meta learning mechanism)

Blog add mailbox private message shortcut
![[fundamentals of machine learning 04] matrix factorization](/img/f5/373bfe68f1a3422e907056c20a0db3.jpg)
[fundamentals of machine learning 04] matrix factorization

Introduction to 51 Single Chip Microcomputer -- digital tube

实训渗透靶场02|3星vh-lll靶机|vulnhub靶场Node1

Xh_CMS渗透测试文档

June 21, 2022: golang multiple choice question, what does the following golang code output? A:3; B:4; C:100; D: Compilation failed. package main import ( “fmt“ ) func

Event preview edgex developer summit @ Nanjing station is coming!

SQL injection vulnerability (XII) cookie injection

【GAN】SAGAN ICML‘19
随机推荐
Introduction to 51 single chip microcomputer - 8x8 dot matrix LED
sessionStorage 和 localStorage 的使用
Fundamentals of neural network (notes, for personal use)
Pytest data parameterization & data driven
[tp6] using the workman websocket
Cactus Song - March to C live broadcast (3)
猿辅导最强暑假计划分享:暑假计划这样做,学习玩耍两不误
leetcode:面试题 08.12. 八皇后【dfs + backtrack】
[Gan] Introduction to Gan basics and dcgan
Theory and application of naturallanguageprocessing
golang調用sdl2,播放pcm音頻,報錯signal arrived during external code execution。
PIP for source changing and accelerated downloading
[out of distribution detection] energy based out of distribution detection nips' 20
Error: unable to find vcvarsall Solutions to bat errors
[M32] simple interpretation of MCU code, RO data, RW data and Zi data
Training penetration range 02 | 3-star VH LLL target | vulnhub range node1
Vue failed to connect to MySQL database
Py之Optbinning:Optbinning的简介、安装、使用方法之详细攻略
Test ofnatural clusters via s-dbscan a self tuning version of DBSCAN
2022年毕业生求职找工作青睐哪个行业?