Node Basics Ten: Session Control

cookie、session、token

1. cookie

A cookie is a small piece of data that the server sends to the client

Cookies are saved according to domain names

Features: When sending a request to the server, the cookie will be automatically set in the request header, and will be destroyed when the browser is closed.

// 设置 cookie
res.cookie('name', 'lisi', { maxAge: 1000 * 60 })
// 删除 cookie
res.clearCookie('name');
// 获取 cookie
npm i cookie-parser
const cookieParser = require("cookie-parser");
app.use(cookieParser());
req.cookies; // { name: 'lisi' }

2. session

session is a piece of data stored on the server

Process: After logging in, the server saves [{ sid: 'xxxx', username: 'lisi', user_id: '1' }], saves the value of sid by setting a cookie, and sends a request next time with a cookie to determine the user's identity by sid

// 设置 session 中间件,生成 sessionId
npm i express-session connect-mongo
const session = require("express-session");
const MongoStore = require("connect-mongo");
app.use(session{
  name: 'sid', // 设置cookie的name
  secret: "yqcoder", // 参与加密的字符串
  saveUninitializad: false, // 是否为每一个请求都设置cookie
  resave: true, // 是否在每次请求后重新保存session
  store: MongoStore({
    mongoUrl: 'mongodb://127.0.0.1:27017/demo'
  }),
  cookie: {
    httpOnly: true, // 开启后前端无法通过js操作
    maxAge: 1000 * 60 // 过期时间
  }
})

// 设置 session 信息
// req.query.username 获取url上的参数
req.session.username = 'yqcoder';
req.session.uid = '888';

// 读取 session 信息
req.session.username

// 销毁 session
req.session.destroy(() => {})

3. The difference between cookie and session

Storage location

cookie: browser

session: server

safety

cookie: less secure

session: relatively good

network transmission

cookie: too much content, affecting transmission efficiency

session: does not affect transmission efficiency

storage limit

cookie: no more than 4k

session: no limit

4. md5 password one-way encryption

npm i md5
const md5 = require("md5");
md5(req.body.password);

5. token

token is a string of encrypted strings generated by the server and returned to the client, and the user information is stored in the token

Features: less pressure on the server side, relatively safer, and more scalable

npm i jsonwebtoken
const jwt = require("jsonwebtoken");

// 创建 token
// jwt.sign(用户数据, 加密字符串, 配置对象)
let token = jws.sign({
  username: 'lisi'
}, 'yqcoder', {
  expiresIn: 60 // 单位秒
})

// 解析 token
let token = req.get('token');
jwt.verify(token, 'yqcoder', (err, data) => {})

Guess you like

Origin blog.csdn.net/weixin_64684095/article/details/132670022