1. 程式人生 > >緩存驗證Last-Modifie和Etag的使用

緩存驗證Last-Modifie和Etag的使用

res tag 讀取 如何 cti eat require function .html

技術分享圖片 看這張圖,是瀏覽器發出請求到請求緩存到過程,這麽一個原理

那麽http裏面如何進行驗證呢?主要有兩個驗證到http頭 Last-Modified(上次修改時間) 主要配合If-Modified-Since或者If-Unmodified-Since使用,什麽意思呢,如果請求一個資源,資源返回上面有Last-Modified這個頭,指定了一個時間,那麽下次請求的時候,就會帶上這個頭,通過If-Modified-Since或If-Unmodified-Since,通常是使用If-Modified-Since,服務器通過If-Modified-Since對比上次給的Last-Modified,驗證資源是否需要更新 Etag
這是一個更嚴格的驗證,就是說我們的資源對他的內容會產生一個唯一的一個簽名,也就是說,如果對這個資源的內容進行了修改,那麽他的簽名就會變成新的,最典型的做法就是對內容進行一個hash計算,下一次瀏覽器發起請求的時候就會帶上If-Match或If-Non-Match使用,這個值就是服務端返回過來的Etag的值,然後服務端對比資源的簽名判斷是否使用緩存
// server.js
const http = require(‘http‘);
const fs = require(‘fs‘);

http.createServer(function(req,res){
  console.log(
‘req come‘, req.url);   if (req.url === ‘/‘) {     const html = fs.readFileSync(‘test.html‘, ‘utf8‘);     res.writeHead(200,{       ‘Content-Type‘: ‘text/html‘     })     res.end(html);   }   if (req.url === ‘/script.js‘) {     res.writeHead(200,{       ‘Content-Type‘: ‘text/javascript‘,       
‘Cache-Control‘: ‘max-age=2000000000, no-cache‘, // 緩存時間很長,但是下次請求時還是需要通過服務端驗證       ‘Last-Modified‘: ‘123‘,       ‘Etag‘: ‘777‘     })     res.end(‘console.log("script loaded")‘);   } }).listen(8888); console.log(‘server listening on 8888‘); console.log(‘http://localhost:8888/‘)
<!--test.html-->
<body>
  <script src=‘/script.js‘></script>
</body>
技術分享圖片

如圖,瀏覽器發送了請求,服務端返回了,Cache-Control,Last-Modified:123,Etag:777,

技術分享圖片

再重新進行一次請求,發現,請求還是像服務端進行了請求,因為no-cache會到服務端驗證,我們看request裏面可以看到,帶了If-Modified-Since:123,If-None-Match:777,但是這個內容其實沒有做任何端更改,這個時候是希望瀏覽器不用返回實際的內容,只需要告訴我們去讀緩存就可以,這個時候應該怎麽做呢,這個時候需要再服務端做個判斷
//server.js
const http = require(‘http‘);
const fs = require(‘fs‘);
 

http.createServer(function(req,res){
  console.log(‘req come‘, req.url);
  if (req.url === ‘/‘) {
    const html = fs.readFileSync(‘test.html‘, ‘utf8‘);
    res.writeHead(200,{
      ‘Content-Type‘: ‘text/html‘
    })
    res.end(html);
  }
 
  if (req.url === ‘/script.js‘) {
    console.log(req.headers);
    const etag = req.headers[‘if-none-match‘];
    if (etag === "777") {
      res.writeHead(304, {
        ‘Content-Type‘: ‘text/javascript‘,
        ‘Cache-Control‘: ‘max-age=2000000000, no-cache‘, // 緩存時間很長,但是下次請求時還是需要通過服務端驗證
        ‘Last-Modified‘: ‘123‘,
        ‘Etag‘: ‘777‘
      })
      res.end(‘‘);
    } else {
      res.writeHead(200,{
        ‘Content-Type‘: ‘text/javascript‘,
        ‘Cache-Control‘: ‘max-age=2000000000, no-cache‘, // 緩存時間很長,但是下次請求時還是需要通過服務端驗證
        ‘Last-Modified‘: ‘123‘,
        ‘Etag‘: ‘777‘
      })
      res.end(‘console.log("script loaded")‘);
    }
  }
}).listen(8888);

console.log(‘server listening on 8888‘);
console.log(‘http://localhost:8888/‘);

技術分享圖片

服務端做了修改,返回了304,但是response是返回有內容的,這是chrome緩存工具會讀取出來,如果寫一些新的內容,再請求,發現還是老的,所以讀的是緩存裏面的內容,把Disable cache鉤上,就會發現請求新的數據了

緩存驗證Last-Modifie和Etag的使用