一、什么是cookie?
cookie是从服务端返回的时候设置Set-Cookie设置到浏览器里面,浏览器保存的这个内容,为我们就叫做cookie。浏览器保存了cookie,在浏览器下一次同域请求当中,就会带上这个cookie,通过cookie一直传输的这个内容,可以保证这个数据一直是这个用户的。可以设置多个cookie.
二、Cookie属性
- max-age和expires设置过期时间
- Secure只在https的时候发送
- HttpOnly无法通过document.cookie访问
三、测试
我们首先建立一个cookie文件夹,下面建立server.js文件,再建立test.html文件。
server.js:
const http = require('http')
const fs = require('fs')
http.createServer(function(request, response) {
console.log('request come', request.url)
if(request.url === '/') {
const html = fs.readFileSync('test.html', 'utf8')
response.writeHead(200, {
'Content-Type': 'text/html',
'Set-Cookie': 'id=123'
})
response.end(html)
}
}).listen(8888)
console.log('server listening on 8888')
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>Contest</div>
</body>
<script>
console.log(document.cookie)
</script>
</html>
然后启动服务,去访问localhost:8888,结果会展示如下:
首先我们去Application下面的Cookies查看:
然后去network查看,然后会发现
四、给cookie设置domain,cookie是限制跨域共享的,可以设置domian,通过domian设置的二级域名,再所有二级域名相同的域名之下,是可以共享cookie的,比如domain设置的是domain=test.com,那么a.test.com和b.test.com是可以共享同一个cookie的。
五、cookie不等于session。