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");
相关推荐
IT策士5 小时前
Redis 从入门到精通:性能调优与多语言客户端对比
数据库·redis·缓存
IronMurphy7 小时前
【算法五十七】146. LRU 缓存
算法·缓存
伊甸39 小时前
从企业级项目学敏感词过滤:DFA算法与双层缓存实战
java·算法·缓存
摇滚侠9 小时前
MyBatis 入门到项目实战 MyBatis 的缓存 56-61
java·缓存·mybatis
IT策士13 小时前
Redis 从入门到精通:Redis Stream —— 可靠消息队列
数据库·redis·缓存
小胖xiaopangss15 小时前
Redis 基础入门与实践指南
数据库·redis·缓存
syt_biancheng1 天前
Redis初识
数据库·redis·缓存
杨运交1 天前
[032][缓存模块]基于Redis Bitmap的用户行为统计实战:签到与日活分析
数据库·redis·缓存
无关86881 天前
Redis Bitmaps 用户签到系统设计方案
数据库·redis·缓存
zzz_23682 天前
【Java基础】链表的七十二变——从LRU缓存到手写浏览器前进后退
java·链表·缓存