1、key value
2、domain 限制某个域可以访问
3、path 表示在那个路径下可以访问cookie /表示任何路径都可以 /read 以路径开头即可
4、expires (绝对时间)/max-age (相对时间)过期时间
5、httpOnly 是否是服务端设置的,前端不能更改
6、如果不设置domain和path 每次请求都会带上cookie
7、一般情况下会设置domain 4k header大小不超过4k Local Storage 5M
8、存在客户端 篡改 拦截 客户端的内容是不安全的。
const http = require("http");
cosnt querystring=require('querystring');
// cookie -> header
let server = http.createServer((req, res) => {
let arr=[];
res.setCookie=function(key,value,options={}){
let opts=[];
if(options.domain){
opts.push(`domain=${options.domain}`);
}
if(options.path){
opts.push(`path=${options.path}`);
}
if(options.httpOnly){
opts.push(`httpOnly=${options.httpOnly}`);
}
if(options.expires){
opts.push(`expires=${options.expires.toGMTString()}`);
}
if(options.maxAge){
opts.push(`max-age=${options.maxAge}`);
}
arr.push(`${key}=${value};${opts.join('; ')}`);
res.setHeader('Set-Cookie',arr);
}
req.getCookie=function(key){
let cookieObj= querystring.parse(req.headers.cookie,'; ');
return cookieObj[key]
}
if (req.url === "/write") {
// key value
// domain 限制某个域可以访问
// path 表示在那个路径下可以访问cookie /表示任何路径都可以 /read 以路径开头即可
// expires (绝对时间)/max-age (相对时间)过期时间
// httpOnly 是否是服务端设置的,前端不能更改
//如果不设置domain和path 每次请求都会带上cookie
//一般情况下会设置domain 4k header大小不超过4k Local Storage 5M
// 存在客户端 篡改 拦截 客户端的内容是不安全的。
/* res.setHeader("Set-Cookie", ["name=message;domain=.whb.cn;path=/;max-age=10",
`age=30;httpOnly=true;expires=${new Date(Date.now()+10*1000).toGMTString()}`]);
res.end("write ok"); */
res.setCookie("name", "message", {
domain: ".whb.cn",
path: "/",
maxAge: 10
});
res.setCookie("age", 10, {
httpOnly: true,
expires: new Date(Date.now() + 10 * 1000)
});
res.end('write ok');
} else if (req.url === "/read") {
// 读取出来的可以是某个字段的结果 aa=123;bb=456; xxx=123
console.log(req.getCookie('name') || "empty");
} else {
res.end("not found");
}
});
server.listen(3000);