cookie、session
1、cookie--浏览器存储数据,在请求服务器的时候,会被带到请求里面
缺点:容量有限(4k),不安全(用户随意篡改)
2、session--只存在服务器端
优点:容量不限,安全(用户看不到)
session基于cookie
风险:如果sessi_ID泄露了--session劫持
1、提醒用户不要在F12的console里面输入
2、session_ID做的非常复杂,有效期,定期更换
cookie:
1、设置
//cookie(name,value,options)
res.cookie('tiany','pawd1111');
2、读取
const cookieParser = require('cookie-parser');
server.use(cookieParser({}));
req.cookies();
*3、安全(防篡改)
console.log(req.cookies);
console.log(signed:
,req.signedCookies);
//cookie(name,value,options)
res.cookie('tiany','pawd1111',{
//domain
//expire:date
//maxAge:int
//path
//secure:true 只用于https
signed: true
});
为啥不签名所有cookie:
1、cookie不是都敏感
2、签名会导致cookie体积扩大
session:
1、设置
req.session[cash
]=1111;
2、读取
req.session
*3、安全(防篡改)
cnpm i cookie-parser cookie-session -D
其他:token
server_cookie.js
const express = require("express");
const cookieParser = require('cookie-parser');
let server = express();
server.listen(3000);
server.use(cookieParser('tianyxxxx'));
server.get('/',(req,res)=>{
console.log(req.cookies);
console.log(`signed:`,req.signedCookies);
//cookie(name,value,options)
res.cookie('tiany','pawd1111',{
//domain
//expire:date
//maxAge:int
//path
//secure:true 只用于https
signed: true
});
res.end();
})
image.png
server_session.js
const express = require("express");
const cookieSession = require('cookie-session');
let server = express();
server.listen(3000);
server.use(cookieSession({
secret:'dasdasd'
}));
//循环秘钥
/*server.use(cookieSession({
secret:[
'dasdasd',
'aaaa',
'bbbb'
]
}));*/
server.get('/',(req,res)=>{
console.log(req.session);
req.session[`cash`]=1111;
if(req.session['count']){
req.session['count']++;
}else{
req.session['count']=1;
}
res.send(`你是第${req.session['count']}次进入此网站`);
res.end();
})
网友评论