69 # 强制缓存的配置

强制缓存

  • 强制缓存:以后的请求都不需要访问服务器,状态码为 200
  • 协商缓存:每次都判断一下,告诉是否需要找缓存,状态码为 304

默认强制缓存,不缓存首页(如果已经断网,那这个页面应该也访问不到,所以首页不会被强制缓存),引用的资源可以被缓存下来,后续找缓存,不会向服务器发送请求

例子:下面设置 10s 内不要在向服务器发送请求

新建 cache.js 文件

javascript 复制代码
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");

const server = http.createServer((req, res) => {
    const { pathname } = url.parse(req.url);
    const filePath = path.join(__dirname, pathname);
    console.log(pathname);
    // expires 老版本浏览器支持的 绝对时间
    // cache-control 相对时间
    res.setHeader("Expires", new Date(Date.now() + 10 * 1000).toGMTString());
    res.setHeader("Cache-Control", "max-age=10");
    fs.stat(filePath, (err, statObj) => {
        if (err) return (res.statusCode = 404), res.end("Not Found");
        // 判断是否是文件
        if (statObj.isFile()) {
            fs.createReadStream(filePath).pipe(res);
        } else {
            res.statusCode = 404;
            res.end("Not Found");
        }
    });
});
server.listen(5000);

然后新建 public 文件夹,里面添加 index.htmlstyle.css

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>凯小默测试强制缓存</title>
</head>

<body>
    <link rel="stylesheet" href="/public/style.css">
</body>

</html>
css 复制代码
body {
    background-color: seagreen;
}

我们启动服务,访问 http://127.0.0.1:5000/public/index.html,加了缓存头之后,css 资源第一次之后就从缓存中读取了,过了 10 s 之后才继续请求一次服务器

bash 复制代码
nodemon cache.js

强制缓存不会向服务器发送请求,所以不会判断缓存是否过期,所以需要设置缓存过期时间,否则缓存永远不会过期,会导致页面修改后,视图依旧采用老的

另外还可以设置响应头:

缓存但是每次都请求服务器

js 复制代码
res.setHeader("Cache-Control", "no-cache");

不在浏览器中进行缓存,每次请求服务器

js 复制代码
res.setHeader("Cache-Control", "no-store");
相关推荐
hcvinh18 小时前
CANDENCE 17.4 进行元器件缓存更新
学习·缓存
墨着染霜华18 小时前
Caffeine的tokenCache与Spring的CaffeineCacheManager缓存区别
java·spring·缓存
weixin_4383354018 小时前
Redis:分组与设备在 Redis 中缓存存储设计
redis·缓存·bootstrap
秋也凉1 天前
redis的命令集合
数据库·redis·缓存
R-sz1 天前
java内存缓存实现 与 redis缓存实现 (ConcurrentHashMap 应用)
java·redis·缓存
好心的小明2 天前
【王树森推荐系统】召回11:地理位置召回、作者召回、缓存召回
人工智能·缓存·推荐系统·推荐算法
草履虫建模2 天前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
程序猿ZhangSir2 天前
Redis 缓存进阶篇,缓存真实数据和缓存文件指针最佳实现?如何选择?
数据库·redis·缓存
段帅龙呀2 天前
Redis构建缓存服务器
服务器·redis·缓存
夜斗小神社3 天前
【黑马点评】(二)缓存
缓存