work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

资源验证

Posted on 2019-03-10 14:03  work hard work smart  阅读(248)  评论(0编辑  收藏  举报

 浏览器请求资源的过程

 

一、验证头

1、Last-Modified 

2、Etag

 

1、Last-Modified 

上次修改时间,

配合If-Modified-Since或者If-Unmodified-Since使用

对比上次修改时间以验证资源是否需要更新。(是否使用上次的缓存)

 

2、Etag

数据签名(数据对应一个签名,典型的应用是对内容进行hash计算,文件名带有hash值)

配合If-Match或者If-Non-Match使用

对比资源签名判断是否使用缓存

 

3、实践

server.js

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

http.createServer(function(request, response){
    console.log('request com', 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"){
      
      

        const etag = request.headers['if-none-match'];
        //no-cache 经过服务器验证,才能使用缓存
        if(etag === '777'){
            response.writeHead(304,{
                'Content-Type':'txt/javascript',
                'Cache-Control': 'max-age=20000000,no-cache', 
                'Last-Modified':'123',
                'Etag':'777'
            })
            response.end('')
        }else{
            response.writeHead(200,{
                'Content-Type':'txt/javascript',
                'Cache-Control': 'max-age=20000000,no-cache', 
                'Last-Modified':'123',
                'Etag':'777'
            })
            response.end('console.log("script load")');
        }

       
    }
   
    


}).listen(8888);

console.log('server listening on 8888')

  

test.html

<html>
    <head>
        <title>Document</title>
    </head>
    <body>

    </body>


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

  

将no-cache 换成no-store,那么本地和代理服务器都不可以存缓存。