nodejs写接口测试浏览器请求304缓存

本文介绍了浏览器缓存策略的概念和作用,通过Node.js编写RESTful缓存接口进行演示。详细讲解了强缓存和协商缓存,强缓存通过设置Expires和Cache-Control实现,协商缓存有Last-Modified与If-Modified-Since、Etag与If-None-Match两种机制,能优化性能、节省带宽。

1 概念和作用

顾名思义 是浏览器将数据暂时缓存在某一位置的方式;

作用:优化浏览器端用户体验的性能;缓存策略是在服务器端设置

        通过浏览器缓存策略可以把从服务器请求的数据缓存在浏览器端;再次请求相同数据,不用发送http请求去服务器端获取数据,第一节省带宽,第二能提高用户体验。

对概念的消化必须建立在实际应用之上;杜绝似懂非懂。所以先用nodejs写几个接口进行测试,一睹为快,更有利于理解概念;

2 一睹为快:nodejs写restful缓存接口演示

2.1 新建一个api_cache.js

,然后在它的同目录执行  node api_cache.js即可(需要安装nodejs环境)

不需要安装别的包,全部使用nodejs内置包实现api 接口;下面代码,我们定义三个请求,一个返回js文件,一个返回图片,一个返回json数据。

// 协商缓存
const http = require('http')
const fs = require('fs')
var path = require('path'); 
let img = fs.readFileSync('./1.png');
http.createServer(function (request, response) {
  // image
  if (request.url === '/img/1') {
      response.writeHead(200, {
        'Content-Type': 'image/png',
    });
    response.end(img);
  }

  // script.js
  if (request.url === '/script.js') {
    response.writeHead(200, {
      'Content-Type': 'text/javascript'
    })
    response.end("");
  }

  // 普通get请求
  if (request.url === '/china') {
    var file = path.join(__dirname, 'china.geojson'); 
    fs.readFile(file, 'utf-8', function (err, data) {
      response.writeHead(200,{
        'Content-Type': 'application/json'
      })
      response.end(data);
    })
  }
}).listen(3000)
console.log("接口服务成功启动在3000接口");

 启动接口如下:

2.2 新建一个test.html,调用我们的接口


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
        <title></title>
        <script src="http://localhost:3000/script.js"></script>
        <script>
            fetch('https://blog.csdn.net/service/http://localhost:3000/china').then(function(res){
                console.log(res)
            })

            let img=new Image()
            img.onload=function(){}
            img.src="http://localhost:3000/img/1"
        </script>
	</head>
	<body>
	</body>
</html>

1.png.script.js和china.json,这三个文件可以自己新建,geojson数据可以在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨大大28

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值