当前位置:网站首页>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

3.1、cookie

3.2、session


  • 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

Stateless protocol :

  1. The protocol has no memory for transaction processing
  2. To the same url The request has no context
  3. 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
  4. The state of the client is not saved in the server , The client must bring its own state to request the server every time
  5. 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}`);
})

原网站

版权声明
本文为[henu_ Newxc03]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112261502154147.html