res.setCookie和req.getCookie的实现(cookie)

24 篇文章 1 订阅

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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vues

刚好遇见你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值