都是规范性的, 不一定
可缓存性:谁可以缓存
public 都可以缓存
private 只有发起请求的浏览器可以 ,nginx缓存 不能用
no-cache 可以缓存 但是要服务器验证 :Last-Modified和Etag
no-store 就是不可缓存
no-transform 代理服务器不可改动缓存内容
到期:
max-age=
s-maxage=
max-stale=
重新验证:
must-revalidate
proxy-revalidate
Cache-Control:private, max-age=0, must-revalidate
该文件是一个私有文件,只能被浏览器缓存,而不能被代理缓存。max-age标识该缓存立即过期,其实和no-cache实际上区别不大. 然后must-revalidate告诉浏览器,你必须给我再验证文件过没过期,比如接下来可能会验证Last-Modified或者ETag.如果没有过期则使用本地缓存.
https://segmentfault.com/a/1190000004486640
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'
})
response.end(html)
}
if (request.url === '/script.js') {
response.writeHead(200, {
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=20'//允许缓存20秒
})
response.end('console.log("script loaded")')
}
}).listen(8888)
console.log('server listening on 8888')
这样的话.如果服务端改了文件.这段时间内客户端都看不到更新了
解决一般是.改引入资源的名字(文件名+hash码) 这样url变了 就不会用老的缓存了
验证
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'
})
response.end(html)
}
if (request.url === '/script.js') {
response.writeHead(200, {
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=2000000,no-cache'//要问过服务器才能用缓存
'Last-Modified': '123',//最后修改 一般写日期
'Etag': '777'//标签 一般是hash
})
response.end('console.log("script loaded")')
}
}).listen(8888)
再次请求,虽然没过期,还是没用缓存
请求头是这样,
为什么没有用缓存?这些都是规范性的,浏览器是实现了,服务器要对验证有一个实现才行,
etag 对上就304,允许浏览器用缓存的
const etag = request.headers['if-none-match']
if (etag === '777') {
response.writeHead(304, {//重点是304 让用缓存
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=2000000, no-cache',
'Last-Modified': '123',
'Etag': '777'
})
response.end(`随便写啥都行,反正浏览器不会用这个`)
}
HTTP 304 未改变说明无需再次传输请求的内容,也就是说可以使用缓存的内容。
Vary
和Cache-Control 一起放响应头里面
Vary: 某头 如X-Test-Cache
这样缓存就按X-Test-Cache 分
请求头里面 X-Test-Cache:1 的 和 X-Test-Cache:2 的只能返回它自己对应的缓存,是不同的