文档

clipboard.png

Last-Modified
  1. 上次修改时间
  2. 配合If-Modified-Since或者If-Unmodified-Since使用
Etag
  1. 数据签名
  2. 配合If-Match或者If-Non-Match使用
  3. 对比资源的签名判断是否使用缓存

文件内容

server3.js
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
    console.log('request come', req.url);
    const html = fs.readFileSync('index.html', 'utf8');
    if (req.url === '/') {
        res.writeHead(200, {
            "Content-Type":"text/html"
        })
        res.end(html)   
    }
    if (req.url === '/script.js') {
        const etag = req.headers['if-none-match'];
        if (etag === '777') {
            res.writeHead(304, {
                "Content-Type": "text/javascript",
                "Cache-Control": "max-age=200000,no-cache",
                'Last-Modified': "123",
                "Etag":"777"
            })
            res.end(' ')   
        } else {
            res.writeHead(200, {
                "Content-Type": "text/javascript",
                "Cache-Control": "max-age=200000,no-cache",
                'Last-Modified': "123",
                "Etag":"777"
            })
            res.end('console.log("script loaded 222")')      
        }
    }
}).listen(8888)
console.log('server start at port 8888')

clipboard.png

clipboard.png

修改server3.js

const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
    console.log('request come', req.url);
    const html = fs.readFileSync('index.html', 'utf8');
    if (req.url === '/') {
        res.writeHead(200, {
            "Content-Type":"text/html"
        })
        res.end(html)   
    }
    if (req.url === '/script.js') {
        const etag = req.headers['if-none-match'];
        if (etag === '777') {
            res.writeHead(304, {
                "Content-Type": "text/javascript",
                "Cache-Control": "max-age=200000",
                'Last-Modified': "123",
                "Etag":"777"
            })
            res.end('123')   
        } else {
            res.writeHead(200, {
                "Content-Type": "text/javascript",
                "Cache-Control": "max-age=200000",
                'Last-Modified': "123",
                "Etag":"777"
            })
            res.end('console.log("script loaded 222")')      
        }
    }
}).listen(8888)
console.log('server start at port 8888')

clipboard.png


渣渣辉
1.3k 声望147 粉丝