yarn add cookie-parser
或者 npm i cookie-parser
//注册
const cookieParser = require('cookie-parser')
app.use(cookieParser())
//设置cookie
app.get("/set_cookie",(req,res) => {
res.cookie('name',"node",{maxAge: 60*60*2})
res.cookie("age",11)
res.send("设置了cookie")
})
//获取cookie
app.get("/get_cookie",(req,res)=>{
let name = req.cookies['name']
let age = req.cookies["age"]
res.send({
name: name,
age:age
})
})
session依赖于cookie
yarn add cookie-session
或者 npm i cookie-session
//注册session
const cookieSession = require('cookie-session')
app.use(cookieSession({
name:"my_session", //命名
keys:["asdaafadsfgdgjsidlyfgulaujhisuhdifgweui"], //加密字段
maxAge: 1000 * 60 * 60 *24 *2 //保存的时间
}))
//设置session
app.get("/set_session",(req,res)=>{
req.session["name"] = "xinghuo"
req.session["age"] = 20
res.send("设置了session")
})
//获取session
app.get("/get_session",(req,res)=>{
let name = req.session["name"]
let age = req.session["age"]
res.send({
name,
age
})
})
这两种方式不能同时使用
yarn add express-session
或 npm i express-session
const expressSession= require("express-session")
app.use(expressSession({
secret:"xinghuo",
resave:false,
saveUninitialized:true
}))
//设置
router.get("/set_eSession",(req,res) =>{
req.session.user = {name:'张三',age:18}
res.send("设置了expressSession")
})
//获取
router.get("/get_eSession",(req,res)=>{
const {user} = req.session
res.send(user)
})