当前位置:网站首页>Nodejs operation state keeping technology cookies and sessions
Nodejs operation state keeping technology cookies and sessions
2022-06-23 21:06:00 【henu_ Newxc03】
Catalog
- because http Is a stateless protocol , The browser request server is stateless .
- No state : When a user requests , browser 、 The server can't know what this user has done before , Every request is a new one .
- No state reason : Browser and server are used socket Socket for communication , After the server returns the request result to the browser , Will close the current socket Connect , And the server will destroy the page object after processing the page .
- Sometimes it's necessary to keep the user's browsing status , For example, whether the user has logged in , What products have you browsed
- There are two main ways to keep the implementation state :
- Store information on the client side
Cookie - Store information on the server side
Session
- Store information on the client side
Stateless protocol :
- The protocol has no memory for transaction processing
- To the same url The request has no context
- Every request is independent , Its execution and results are not directly related to the previous request and subsequent request , It will not be directly affected by the previous request response , It will not directly affect the subsequent request response
- The state of the client is not saved in the server , The client must bring its own state to request the server every time
- Life if only as first see
Status example :
- A stateful :
- A: What did you have for lunch today ?
- B: Eat a large plate of chicken .
- A: How does it taste ?
- B: Not bad , Good to eat .
- No state :
- A: What did you have for lunch today ?
- B: Eat a large plate of chicken .
- A: How does it taste ?
- B:??? ah ? what ? What does it taste like ?
- So we need to cookie This kind of thing :
- A: What did you have for lunch today ?
- B: Eat a large plate of chicken .
- A: What's the taste of the big dish of chicken you ate this noon ?
- B: Not bad , Good to eat .
3.1、cookie
characteristic :
1、cookie Generated by the server , A short piece of text information saved on the browser side
2、cookie Is stored as keys and values
3、 When a browser accesses the server of a website , It will automatically put all the information related to this website in the request header cookie Send to the server
4、cookie It's based on domain name security
5、cookie There is an expiration date , Expires after closing the browser by default
Use :
First install and introduce :cookie-parser
Sign up to app in :
const cookieParase = require('cookie-parser');
app.use(cookieParase());Set up cookie:res.cookie('name', "node", {maxAge: 1000 * 60 * 60 * 2 });
obtain cookie:let name = req.cookies["name"]
The complete code is as follows :
// 1、 install cookie-parser
// 2、 introduce cookie-parser And register to the app in
const cookieParase = require('cookie-parser');
app.use(cookieParase());
app.get("/setCookie",(req,res)=>{
// Set up cookie
res.cookie('name', "node", {maxAge: 1000 * 60 * 60 * 2 }); // Expiration time : Unit millisecond
res.cookie('age', 11);
res.send(" Set up cookie")
})
app.get("/getCookie",(req,res)=>{
// obtain cookie Information
let name = req.cookies["name"];
let age = req.cookies["age"];
res.send(` obtain cookie, ${name}, ${age}`);
})3.2、session
characteristic :
1、session Data is saved on the server side
2、session Is stored in the form of keys and values
3、session Depend on cookie, Every session The identification of the client corresponding to the information is saved in cookie in
Use :
First install and introduce :cookie-session
const cookieSession = require('cookie-session');Sign up to app in :
app.use(cookieSession({
name:"my_session", //name by session name , Just start a string by yourself
keys:["$^%%&^&%$RT%&TYGSGSFRR554785432$#@$$#%[email protected]#%"], // Internal encryption requires keys, keys For random strings
maxAge: 1000 * 60 * 60 * 24 // Expiration time
}))Set up session:req.session["name"] = "session_node"
obtain session:let name = req.session["name"]
The complete code is as follows :
// 1、 Install first :yarn add cookie-session // If you make a mistake , Add version number later , Then just keep returning yarn add [email protected] // 2、 Set to app in const cookieSession = require('cookie-session'); app.use(cookieSession({ name:"my_session", //name by session name , Just start a string by yourself keys:["$^%%&^&%$RT%&TYGSGSFRR554785432$#@$$#%[email protected]#%"], // Internal encryption requires keys, keys For random strings maxAge: 1000 * 60 * 60 * 24 // Expiration time })) app.get("/setSession",(req,res)=>{ // Set up session req.session["name"] = "session_node" req.session["age"] = 11 res.send(" Set up Session") }) app.get("/getSession",(req,res)=>{ // obtain session Information let name = req.session["name"] let age = req.session["age"] res.send(` obtain Session, ${name}, ${age}`); })
边栏推荐
- Is Guoyuan futures trading software formal? How to download safely?
- What is the main content of short video audit? What is illegal?
- What are the server host security risks? How to prevent safety risks?
- WinDbg loads mex DLL analysis DMP file
- What is the difference between object storage and cloud disk service? What are the functions of cloud disk service?
- Summary of multiple methods for obtaining the last element of JS array
- December 29, 2021: the elimination rules of a subsequence are as follows: 1. In a subsequence
- 【Golang】来几道题以加强Slice
- How to build a cloud game platform on the server? How to select a cloud game server?
- [5 minutes to play lighthouse] quickly use Chang'an chain
猜你喜欢
随机推荐
Is it safe for flush to open an account online? Is the Commission high
Yukeng MySQL service installation error
手续费佣金低的券商,华泰证券网上开户安全吗
游戏安全丨喊话CALL分析-写代码
JS five methods to judge whether a certain value exists in an array
[golang] quick review guide quickreview (x) -- goroutine pool
Short video intelligent audit software intelligent audit or manual audit
How to process the text of a picture into a table? Can the text in the picture be transferred to the document?
【Golang】快速复习指南QuickReview(六)——struct
How to make a commodity price tag
Whether the offsetwidth includes scroll bars
What is the role of short video AI intelligent audit? Why do I need intelligent auditing?
2021 three "myths" of science and technology industry -- yuancosmos, NFT and web 3
How to build Tencent cloud game server? Differences between cloud game platforms and ordinary games
How to handle the prompt that DNS is incorrect when adding resolution to Tencent cloud?
JS takes two decimal places
Is it possible to transfer files on the fortress server? How to operate?
Row height, (top line, middle line, baseline, bottom line), vertical align
What cloud disk types does Tencent cloud provide? What are the characteristics of cloud disk service?
Emmet syntax specification


