69 # 强制缓存的配置

强制缓存

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

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

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

新建 cache.js 文件

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

<!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>
body {
    
    
    background-color: seagreen;
}

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

nodemon cache.js

在这里插入图片描述

在这里插入图片描述

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

另外还可以设置响应头:

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

res.setHeader("Cache-Control", "no-cache");

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

res.setHeader("Cache-Control", "no-store");

猜你喜欢

转载自blog.csdn.net/kaimo313/article/details/132352992
69
69A
今日推荐