緩存工作示意圖:
在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")') }