一、什麼是 if-modified-since
if-modified-since 是一個 HTTP 協議中的頭信息,其作用是告訴伺服器獲取資源的時間。與資源上次修改時間進行對比,判斷是否需要重新獲取資源。
如果客戶端已經有過該資源,而該資源沒有發生任何修改,那麼伺服器會返回狀態碼為 304。這時客戶端就可以直接使用本地緩存的該資源,從而提高頁面的載入速度。
二、 if-modified-since 的實現原理
if-modified-since 使用的是 HTTP 協議中的條件請求機制。它是通過客戶端在請求頭中加上 If-Modified-Since 欄位來實現的。
當客戶端第一次請求資源時,伺服器會將該資源的相關信息以及 Last-Modified 欄位一起返回給客戶端。客戶端將 Last-Modified 存儲在緩存中。
當客戶端再次請求資源時,在請求頭中添加 If-Modified-Since 欄位,其值為客戶端記錄的 Last-Modified 值。伺服器接收到請求後,會將該值與該資源的 Last-Modified 值進行比較。若相同,則返回 304 狀態碼,告訴客戶端使用本地緩存。否則伺服器會返回新的資源,並更新 Last-Modified 值。
三、 if-modified-since 的應用場景
if-modified-since 主要用於靜態資源的緩存,比如圖片、CSS、JS 等。這樣客戶端在第一次請求之後,如果該資源沒有發生變化,就可以使用本地緩存,提高網頁載入速度。
除了靜態資源以外,if-modified-since 還可以用於動態頁面的緩存。比如在博客網站上,可以使用 if-modified-since 緩存博客文章頁面。這樣當用戶二次訪問同一篇文章時,如果文章沒有發生修改,就可以直接使用本地緩存,提高打開速度。
四、 if-modified-since 的使用示例
// 伺服器端代碼 const fs = require('fs'); const http = require('http'); const path = require('path'); const server = http.createServer((req, res) => { const filename = path.join(__dirname, 'public', req.url); fs.stat(filename, (err, stats) => { if (err) { res.statusCode = 404; res.end('404 Not Found'); return; } const lastModified = stats.mtime.toUTCString(); if (req.headers['if-modified-since'] === lastModified) { res.statusCode = 304; res.end(); return; } res.setHeader('Last-Modified', lastModified); fs.createReadStream(filename).pipe(res); }); }); server.listen(3000, () => { console.log('Server is listening on port 3000'); });
// 客戶端代碼if-modified-since Demo
以上代碼是一個簡單的 Node.js HTTP 伺服器和一個使用 if-modified-since 的客戶端網頁。使用 Node.js 的 fs 模塊讀取靜態文件,判斷請求頭中的 if-modified-since 欄位與該文件的修改時間是否一致。如果一致,伺服器會返回 304 狀態碼,否則會返回該文件和修改時間,客戶端將該值緩存。
原創文章,作者:HTLU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/144431.html