1.基本配置
1.下载cookie
npm install cookie-parse --save
2.引入cookie
var cookieParser=require('cookie-parser')
3.配置中间件
app.use(cookieParser('itying'))
这里面的itying是随便写的,是给加密用的
2.写入cookie
username:表示字段名
zhangsan:表示字段值
{}:这里面的是配置信息
{maxAge:1000*60}:表示1分钟后失效
{signed:true}:表示要进行加密
app.get('/index',function(req,res){
res.cookie('username','zhangsan',{maxAge:1000*60}) // 设置cookie
res.send('你好 express')
res.end()
})
访问http://localhost:8090/indexindex即可写入成功
3.访问cookie
app.get('/login',(req,res)=>{
let username=req.cookies.username; // 获取cookie
console.log(username);
res.send('name is '+username)
res.end()
})
通过访问:http://localhost:8090/login 即可读取
4.写入加密的cookie
app.use(cookieParser('itying'))//中间件里要写点东西,随便写点
app.get('/index',function(req,res){
res.cookie('username','zhangsan',{maxAge:1000*60,signed:true}) // signed:true设置加密的cookie
res.send('你好 express')
res.end()
})
图片可看出加密了
5.读取加密的cookie
app.get('/product',(req,res)=>{
let username=req.signedCookies.username;// 获取加密cookie
console.log(username);
res.send('name is '+username)
res.end()
})
虽然加密了但还是可以读取
而且你给他改了,会显示false