緩存驗證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")') }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM