缓存验证Last-Modified和Etag的使用

缓存工作示意图:

 

 在http协议里面,数据的验证方式,主要有两个验证头:Last-Modified 和 Etag。

  Last-Modified 配合Last-Modified-Since或者If-Unmodified-Since使用,对比上次修改的时间验证资源是否需要更新。

  Etag 是一个更加严格的数据验证。数据签名[根据数据的内容进行签名,如果数据内容变了,Etag也会变],最典型

     的Etag数据签名就是hash计算。配合If-Match或者If-Non-Match使用,对比资源的签名判断是否使用缓存。

if (request.url === '/script.js') {
  response.writeHead(200, {
     'Content-Type': 'text/javascript',
     'Cache-Control': 'max-age=200000, no-cache',
     'Last-Modified': '123',
     'Etag': '777' 
  })
  const etag = request.headers['if-none-match']

if (etag === '777') { response.writeHead(304, { // 304 表示内容没有变 'Content-Type': 'text/javascript', 'Cache-Control': 'max-age=200000, no-cache', 'Last-Modified': '123', 'Etag': '777' }) response.end('') } else { response.writeHead(200, { 'Content-Type': 'text/javascript', 'Cache-Control': 'max-age=200000, no-cache', 'Last-Modified': '123', 'Etag': '777' }) response.end('console.log("script loaded twice")') }

 

posted @ 2020-02-21 12:49  ladybug7  阅读(1009)  评论(0编辑  收藏  举报