# 浏览器缓存

# 1、强制清除某个一资源的缓存

场景:当编辑一张图保存后,再次刷新页面 img 标签获取的图片还是缓存数据,在不变更 src 图片地址的情况下如何获取最新的图片

解决思路:每次获取改图片时,取得改图片资源的 lastModifiedetag,当需要更新资源的时候,发送更新请求

const response = await axios.get('http://test.com/test.jpg', {
  responseType: 'blob',
});
let etag = response.headers['etag'];
let lastModified = response.headers['last-modified'];

img.src = URL.createObjectURL(response.data); // 显示图片
1
2
3
4
5
6
7

更新图片资源:

const options = {
  headers: {
    'Cache-Control': 'max-age=0',
    'If-Modified-Since': lastModified, // 根据 lastModified 和 etag 更新图片资源
    'If-None-Match': etag,
  },
};
await axios.get(url, options);
1
2
3
4
5
6
7
8

经过测试,直接用浏览器打开该图片资源,打开控制台,再次刷新页面,可以看到浏览器发出的请求里面包含 Cache-ControlIf-Modified-SinceIf-None-Match 三个字段请求头

上次更新: 8/31/2024, 10:47:42 AM