Use session and cookie in express

The working mechanism of cookie and session:

Since cookies are stored on the client side, sensitive information cannot be stored, while sessions are stored on the server side and can be used to store sensitive information. For example, the preservation of the user's login status. But http is stateless. How does the session save the user login status? When the user logs in successfully, the server will correspond to a session data with the user information, and send the key to obtain the session data to the client, and the key is in The saving form of the client is saved in a cookie. When the user visits other webpages of the current website again, the cookie information is sent to the server together. When the server receives the key saved in the cookie, it checks the session data corresponding to the key, thereby Determine whether the user is logged in. If you are logged in, you can directly access it, otherwise you will be redirected to the login page.

In the express framework, Session and Cookie are not supported by default, but third-party middleware can be used express-sessionto solve the problem.

download:

npm install --save express-session

Configuration

var session = require('express-session'); # 引入

# 配置中间件
app.use(session({
    
    
  // 配置加密字符串,会在原有加密基础上和这个字符串拼起来去加密
  // 目的是:增加安全性,防止客户端恶意伪造
  secret: 'chen',
  resave: true,
  // 当为false,表示只有使用session,才会分配钥匙
  // 当为true,表示无论是否使用session,都会分配钥匙
  saveUninitialized: false
}))

use

#req.session.xx = xx表示设置session(对象)
# req.session.xx 表示获取session数据
app.get('/',(req,res) => {
    
    
    # 当访问/的时候,设置当前session值,并将session钥匙回传给客户端,保存在客户端的cookie中
  req.session.uname = 'chen';
  res.render('index.html',{
    
    
    name: 'chen'
  })
})

app.get('/a',(req,res) => {
    
    
    // 当访问/a的时候,获取session数据
  console.log(req.session.uname);
  res.send('ok');
})

Guess you like

Origin blog.csdn.net/chen__cheng/article/details/115063321