http的缓存学习记录
强缓存
1. expire
浏览器根据后端的响应头的expire字段,判断当前的资源是否过期,设置方法。该方法缺陷是由浏览器控制缓存是否失效。浏览器的时间可以随意调整,不能有效的控制缓存。
resp.setHeader("Expires", new Date(Date.now() + 10*1000).toUTCString());
2. cache-Control
服务端在设置经过多长时间该资源失,设置方法如下,单位是秒。
resp.setHeader("Cache-Control","max-age=20");
协商缓存
设置浏览器使用协商缓存(前提)
resp.setHeader("Cache-Control", "no-cahce");
1. 基于修改时间 last-modified和if-modified-since
服务端设置了响应头last-modified后返回给浏览器,浏览器下次请求该资源的时候,在请求头中添加if-modified-since字段把第一次的last-modified的值设置进去。后端判断请求是否过期。
resp.setHeader("last-modified", new Date().toUTCString());
const ifModifiedSince = req.headers["if-modified-since"];
const isModified = new Date(ifModifiedSince).getTime() + 10 * 1000 > Date.now();
if (isModified) {
resp.statusCode = 304;
resp.end();
return;
}
2. 基于内容hashEtag和if-none-match
服务端设置响应头Etag=资源的hash值,返回给浏览器,浏览器下次请求该资源的时候,在请求头中添加if-none-match字段,把缓存中内容的hash值设置进去,发送给后端,后端判断内容是否过期。
const hash = crypto.createHash("sha1").update(content).digest("hex");
resp.setHeader("Etag", hash);
console.log(req.headers["if-none-match"],hash,req.headers["if-none-match"] == hash);
const isMatch = req.headers["if-none-match"] == hash;
if (isMatch) {
resp.statusCode = 304;
resp.end();
return;
}
resp.statusCode = 200;
resp.end(content);