鲜荣彬
Herry

含义:

     消息头字段被用于在http 请求和响应中通过指定指令来实现缓存机制。

使用:

  指令不区分大小写,并且具有可选参数,可以用令牌或者带引号的字符串语法。多个指令以逗号分隔。

常用的指令:

  1、可缓存性

  2、到期

  3、重新验证与重新加载

 1 /*
 2 * public  表明响应可以被任何对象(包括:发送请求的客户端,代理服务器,等等)缓存。
 3 * private 发起缓存的浏览器才能缓存
 4 * no-cache 可以在本地缓存,每次发起请求,都要去服务器验证是否可以用本地缓存
 5 * max-age=<秒>
 6 * s-maxage=<秒>   取代max-age只有代理服务器里才会生效
 7 * max-stale=<秒>   表明客户端愿意接收一个已经过期的资源。 可选的设置一个时间(单位秒),表示响应不能超过的过时时间。
 8 * must-revalidate  max-age已经过期,必须从源服务端重新获取验证
 9 * proxy-revalidate  用在缓存服务器中,缓存服务器过期
10 *
11 * no-store
12 * no-transform  用在代理缓存服务
13 * 限制性,申明性,但是没有强制使用
14 * */

  下面的Demo,使用Node建立服务器,去验证使用缓存后的效果。

const http=require('http');
const fs=require('fs');

http.createServer((request,response)=> {
    const html = fs.readFileSync('main.html', 'utf8');
    if(request.url ==='/'){
        response.writeHead(200,{
            'Content-Type':'text/html'
        });
        response.end(html);
    }

    if(request.url ==='/cacheScript.js'){
        let time = new Date();
        response.writeHead(200,{
            'Content-Type':'application/x-javascript',
            'Cache-Control':'max-age=10,private,s-maxage=3'
            // 浏览器最大缓存时间是3秒,超过3秒后,重新获取服务器资源
        });
        response.end(time.toLocaleDateString());
    }
}).listen(8888)
<body>
<script src="cacheScript.js"></script>
<h1>hello,cache control</h1>
</body>

测试结果可知,cacheScript.js脚本,在请求三秒之内,是从内存缓存中获取的。

posted on 2019-02-28 15:46  Herry彬  阅读(445)  评论(0)    收藏  举报