浏览器请求资源的过程
一、验证头
1、Last-Modified
2、Etag
1、Last-Modified
上次修改时间,
配合If-Modified-Since或者If-Unmodified-Since使用
对比上次修改时间以验证资源是否需要更新。(是否使用上次的缓存)
2、Etag
数据签名(数据对应一个签名,典型的应用是对内容进行hash计算,文件名带有hash值)
配合If-Match或者If-Non-Match使用
对比资源签名判断是否使用缓存
3、实践
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,那么本地和代理服务器都不可以存缓存。
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!