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");
相关推荐
wclass-zhengge10 小时前
Redis篇(最佳实践)(持续更新迭代)
redis·缓存·bootstrap
Dylanioucn10 小时前
【分布式微服务云原生】探索Redis:数据结构的艺术与科学
数据结构·redis·分布式·缓存·中间件
小小娥子1 天前
Redis的基础认识与在ubuntu上的安装教程
java·数据库·redis·缓存
DieSnowK1 天前
[Redis][集群][下]详细讲解
数据库·redis·分布式·缓存·集群·高可用·新手向
PYSpring1 天前
数据结构-LRU缓存(C语言实现)
c语言·数据结构·缓存
CoderJia程序员甲1 天前
重学SpringBoot3-集成Redis(一)
java·redis·缓存·springboot
周周写不完的代码1 天前
redis-数据类型
数据库·redis·缓存
Tonvia1 天前
猫猫cpu的缓存(NW)
算法·缓存
白总Server1 天前
CNN+Transformer在自然语言处理中的具体应用
人工智能·神经网络·缓存·自然语言处理·rust·cnn·transformer
周周写不完的代码2 天前
Redis-持久化机制
数据库·redis·缓存