浏览器请求资源的过程javascript
1、验证头html
一、Last-Modified java
二、Etag浏览器
一、Last-Modified 缓存
上次修改时间,服务器
配合If-Modified-Since或者If-Unmodified-Since使用ui
对比上次修改时间以验证资源是否须要更新。(是否使用上次的缓存)url
二、Etag代理
数据签名(数据对应一个签名,典型的应用是对内容进行hash计算,文件名带有hash值)server
配合If-Match或者If-Non-Match使用
对比资源签名判断是否使用缓存
三、实践
server.js
const http = require('http'); const fs = require('fs') http.createServer(function(request, response){ console.log('request com', request.url) if(request.url === "/"){ const html = fs.readFileSync('test.html','utf8') response.writeHead(200,{ 'Content-Type':'text/html' }) response.end(html) } if(request.url === "/script.js"){ const etag = request.headers['if-none-match']; //no-cache 通过服务器验证,才能使用缓存 if(etag === '777'){ response.writeHead(304,{ 'Content-Type':'txt/javascript', 'Cache-Control': 'max-age=20000000,no-cache', 'Last-Modified':'123', 'Etag':'777' }) response.end('') }else{ response.writeHead(200,{ 'Content-Type':'txt/javascript', 'Cache-Control': 'max-age=20000000,no-cache', 'Last-Modified':'123', 'Etag':'777' }) response.end('console.log("script load")'); } } }).listen(8888); console.log('server listening on 8888')
test.html
<html> <head> <title>Document</title> </head> <body> </body> <script src="/script.js"></script> </html>
将no-cache 换成no-store,那么本地和代理服务器都不能够存缓存。