缓存
强缓存
Expires
http1.0定义的缓存响应字段
res.setHeader("Expires", new Date(Date.now() + 20 * 1000).toUTCString());
特点:时间戳,客户端再次发送请求,会在客户端作比对。请求没到服务端
缺点:不能保证服务器和客户端是一致的,时间不准确
cache-control
http1.1定义的缓存响应字段,优先级比Expires高
res.setHeader("Cache-Control", "max-age=20");
特点:如果设置了no-cache和no-store,本地缓存会被忽略,会直接请求服务器
缺点:更新规则比较复杂时,需要访问服务端
协商缓存
都会请求到服务器
last-modified & if-Modified-Since
以修改时间为基础
res.setHeader("Cache-Control", "no-cache");
res.setHeader("last-modified", new Date().toUTCString());
const clientSince = req.headers["if-modified-since"];
if (new Date(clientSince).getTime() + 5 * 1000 > Date.now()) {
console.log("缓存命中");
res.statusCode = 304;
res.end();
return;
}
Etag & if-none-match
以文件内容为基础
const crypto = require("crypto");
const hash = crypto.createHash("sha1").update(content).digest("hex");
res.setHeader("Etag", hash);
if (req.headers["if-none-match"] === hash) {
console.log("Etag缓存命中");
res.statusCode = 304;
res.end();
return;
}