Cookie基础知识

服务器的响应头(Response-Headers)设置Set-Cookie时,发送请求的时候cookie就会写入到浏览器中,浏览器在下次请求就会携带cookie。

node设置单个cookie,代码如下:

response.writeHead(200, {
    "Content-Type" : "text/html",
    "Set-Cookie": ["id=123"]
});

浏览器中:
这里写图片描述


node设置多个cookie,代码如下:

response.writeHead(200, {
    "Content-Type" : "text/html",
    "Set-Cookie": ["id=123", "abc=456"]
});

浏览器中:
这里写图片描述


Cookie是可以设置过期时间,浏览器关闭的时候,cookie就会失效。

设置2s过期时间,代码如下: (id=123对应的cookie在2s后会失效)

response.writeHead(200, {
    "Content-Type" : "text/html",
    "Set-Cookie": ["id=123; max-age=2", "abc=456"]
});

cookie为了安全起见,可以禁止js去访问cookie,代码如下:(通过document.cookie是无法去访问的)

response.writeHead(200, {
    "Content-Type" : "text/html",
    "Set-Cookie": ["id=123;", "abc=456; HttpOnly"]
});

在页面中通过document.cookie仅仅可以访问到id=123,而无法访问abc=456


另外可以通过设置domain,让主域名的所有二级域名都可以访问cookie。
代码如下:

response.writeHead(200, {
    "Content-Type" : "text/html",
    "Set-Cookie": ["id=123; max-age=2", "abc=456; domain=test.com"]
});

在test.com里设置domain=test.com, 所有a.test.com b.test.com 等二级域名都可以访问此cookie

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值