浏览器缓存问题Cache-Control

阅读此文:你可以更好理解浏览器缓存问题,也可以看到一个简单的http服务与客户端请求。
问题:
有浏览器缓存可以方便我们加载资源,不重复请求。增强用户体验度。但是存在问题,当服务器端更新资源的时候,往往会由于浏览器请求的是缓存的资源,而导致页面无法更新。
这个问题解决方案如下:在构建流程的时候,在实践打包完成的文件名上,去根据他们的内容加上一串hash码,这串hash码是根据js\html\css内容来编码的,他们的内容进行hash计算,如果你的js文件或者静态文件其内容不变,hash码也不会变,竟而反应到我们web就是我们的URL没有变。而如果你的内容有变化,那你的hash码就有变化,就会反应在你的url上。这url路径就会有变化。有了变化后,它发起的请求就是新的求,而不是之前缓存在浏览器中的请求。这样就可以达到一个更新缓存的目的。
server1.js

const http = require('http')
const fs =  require('fs');

http.createServer(function(request,response){
  console.log('request come',request.url)
   if( request.url === '/'){
    const html =fs.readFileSync('test.html','utf8')
    response.writeHead(200,{
        'Content-Type':'text/html'
    })
     // 服务器返回内容
    response.end(html)
   }
   if( request.url === '/script.js'){
    response.writeHead(200,{
        'Content-Type':'text/javascript',
        'Cache-Control':'max-age=20'
    })
    // 服务器返回内容
    response.end('console.log("script loaded")')
   }
}).listen(8888)
console.log("server listening 8888")
// 2定义了以fs为协议的fs对象
// 6以utf8的方式去读取test.html
// 返回的头是200 文本类型是'Content-Type':'test/html' 来解析的

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
      Hello World  jajajpfajfpajfpa 
</body>
</html>

<script src="/script.js"></script>

怎么查看Cache-Control

在你要访问的服务端页面上设置 ‘Cache-Control’:‘max-age=20’ 这个配置,这样再次刷新页面的时候,就会得到之前缓存过后的数据。直接在浏览器本地里面读取,就不需要去服务器请求。就没有网络延迟的操作。可以在NetWork里面看到Headers有个Cashe-Control:max-age=20;注意一定要Disable cache勾掉。允许缓存。size:(from memory cache);Time:0ms;
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_35209064/article/details/85467946