IoT Web应用read.json缓存导致响应延迟问题求助
问题分析与解决方案
核心原因
闲置后请求read.json返回200 (from disk cache),说明浏览器将该文件缓存到磁盘。闲置期间Python脚本已更新服务器上的read.json,但浏览器仍读取本地缓存的旧数据,直到手动触发新请求(比如直接打开文件)才会获取最新内容。
解决方法
1. 前端请求添加缓存破击参数
在请求URL后追加唯一时间戳,让每次请求的URL都不同,浏览器不会复用缓存:
foo(); function foo() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { /*do stuff using "this.responseText"*/ } }; // 追加时间戳确保URL唯一,规避缓存 xhttp.open("GET", "https://www.mydomain.example/read.json?t=" + Date.now(), true); xhttp.send(); setTimeout(foo, 100); }
2. 服务器端设置缓存控制头
从根源控制缓存策略,强制浏览器每次从服务器拉取最新内容:
- 若通过PHP生成
read.json,在脚本开头添加响应头:
header("Cache-Control: no-cache, no-store, must-revalidate"); header("Pragma: no-cache"); header("Expires: 0"); // 输出read.json内容
- 若用Nginx配置,针对
read.json添加缓存规则:
location /read.json { add_header Cache-Control "no-cache, no-store, must-revalidate"; add_header Pragma "no-cache"; add_header Expires "0"; }
3. 前端请求头禁用缓存
在XMLHttpRequest中设置请求头,告知浏览器不要使用缓存:
foo(); function foo() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { /*do stuff using "this.responseText"*/ } }; xhttp.open("GET", "https://www.mydomain.example/read.json", true); // 添加请求头禁用缓存 xhttp.setRequestHeader("Cache-Control", "no-cache"); xhttp.setRequestHeader("Pragma", "no-cache"); xhttp.send(); setTimeout(foo, 100); }
方案选择
- 快速临时修复:用方法1,无需修改服务器配置,前端直接调整即可生效。
- 长期根治:用方法2,所有访问该文件的客户端都会遵循缓存规则,避免前端重复处理。
- 特定请求控制:用方法3,适合仅需对单个请求禁用缓存的场景。
内容的提问来源于stack exchange,提问作者Xframe22
相关产品推荐
相关产品推荐

