服务器的响应头(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