浏览器和服务器之间经过 (ETag, If-None-Match ) (Last-Modified ,If-Modified-Since) 这两对请求头和响应头的信息,来判断请求是否过时! 注意,不管是请求静态资源,仍是请求动态内容,在HTTP协议这一层处理是一致的,并非只有资源才会缓存。javascript
仍是动手一下印象深入:java
const http = require('http'); const hostname = '127.0.0.1'; const port = 8000; const server = http.createServer((req, res) => { if (req.headers['if-modified-since'] == 'abc') { res.statusCode = 304 res.end(); } else { res.statusCode = 200; res.setHeader("Last-Modified", "abc") res.setHeader('Content-Type', 'text/plain'); res.end('Hello Worl\n'); } }); server.listen(port, hostname, () => { console.log(`服务器运行在 http://${hostname}:${port}/`); });
第一次请求,响应头会带上Last-Modified 头。 第2次请求会使用缓存!请在浏览器中动手试一下就明白了浏览器