#Cache-Control适用场合 该参数用于缓存控制,在设置了该值后,浏览器会在超过该时间的情况下强行请求一次服务器,否则会一直使用上一次访问时的数据。 例如max-age=60,这里就告诉了浏览器在60秒内可以使用缓存,超过后需要重新向服务器发送请求。 这里要注意的事文件的访问方式局限于该文件是被其它文件所调用,或者是在新窗口访问该文件,如果在访问单个文件时使用了浏览器上的刷新按钮,那么就会浏览器就会强行触发一次发向服务器的请求。 这也就为什么很多人发现Cache-Control设置失效的原因。 #ETag的作用 该值一般是由服务器端生成的一段随机代码,用于指示当前访问文件的特殊值(文件的任何改变都会导致其改变)。一般用于校验当前文件是否是最新的文件。 #Cache-Control结合ETag的用法 在后台获取当前文件的ETag值,并设置,当Cache-Control缓存过期时,后端先判断请求头的'If-None-Match'是否和当前Etag相等,如果相等的话,那么直接返回304http状态,指示浏览器可以继续使用当前的缓存内容。这样可以节省很多的网络请求同时还能提高访问速度。 下面是一个示范 ```js var path = require('path'); var fs = require('fs'); var thunkify = require('thunkify'); var koa = require('koa'); var render = require('koa-swig'); var app = koa(); var staticCache = require('koa-static-cache'); var stat = thunkify(fs.stat); var etag = require('etag') app.context.render = render({ root: path.join(__dirname, 'views'), autoescape: true, cache: false, ext: 'html' }); app.use(function* index(next){ app.context.indexfile = yield stat(path.join(__dirname,'views/index.html')); console.log('hit'); this.status = 200; this.set({ "ETag": etag(this.indexfile), 'Last-Modified': this.indexfile.ctime.toUTCString() }); this.set({ 'Cache-Control':'no-cache' }); if (this.fresh){ this.status = 304; this.response.remove('Content-Type'); this.response.remove('Content-Length'); return; } yield this.render('index'); }); if (!module.parent) { app.listen(3000); } ```