cookie
通过Set-Cookie设置,里面的内容我们就叫cookie
下次请求的时候会自动带上
cookie是以健值对的形式设置,可以设置多个
cookie的属性
max-age和expires设置过期时间
secure只在https的时候发送
HttpOnly无法通过document.cookie访问(防止被攻击)
使用
//server.js const http = require('http'); const fs = require('fs'); http.createServer(function(req,res){ console.log('req come', req.url); if (req.url === '/') { const html = fs.readFileSync('test.html', 'utf8'); res.writeHead(200,{ 'Content-Type': 'text/html', 'Set-Cookie': 'id=123' }) res.end(html); } }).listen(8888); console.log('server listening on 8888'); console.log('http://localhost:8888/');
<!--test.html--> <body> <div>Content</div> <script> console.log(document.cookie) </script> </body>
启动服务,访问8888端口,可以看到打印出来了console,访问到了,cookie设置里面有内容,每次返回的时候也带上了Set-Cookie
![](https://img2018.cnblogs.com/blog/331769/201812/331769-20181207070039484-862097947.png)
cookie是可以设置多个的
'Set-Cookie': ['id=123','abc=456']
![](https://img2018.cnblogs.com/blog/331769/201812/331769-20181207070122771-1638008424.png)
如图,多个cookie是通过数组实现的,看到两个Set-Cookie,application里面保存了两个
cookie是存在时效的,把浏览器关了,再访问,就发现network没有了cookie,application里面是清空了重新存储的,再重新发送,就发现req又带上了cookie
'Set-Cookie': ['id=123;max-age=2','abc=456']
设置了,123过期时间,看下实际效果
![](https://img2018.cnblogs.com/blog/331769/201812/331769-20181207070211085-977389764.png)
再刷新,发现req里面只带了456
cookie的HttpOnly
'Set-Cookie': ['id=123; max-age=2','abc=456; HttpOnly']
保存,启动,刷新,
发现只访问到了123,再把HttpOnly去掉
发现123,456都访问到了,这就是禁止js访问的作用
cookie不同域不能共享cookie,二级域名一样可共享cookie