面试之《网络请求的资源如何强制不缓存》

在前端开发中,要强制网络请求的资源不被缓存,可以通过设置 HTTP 头信息以及在前端代码中进行相应配置来实现。以下是一些常见的方法,分别从服务端和前端角度进行介绍:

服务端设置(以常见的 Web 服务器为例)

  1. Apache 服务器
    .htaccess 文件中添加以下代码,可以针对特定类型的文件(如 JavaScript、CSS、图片等)设置不缓存:
apache 复制代码
<IfModule mod_headers.c>
    <FilesMatch "\.(js|css|png|jpg|gif)$">
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires "0"
    </FilesMatch>
</IfModule>

上述代码中,Cache-Control 字段设置为 no-cache, no-store, must-revalidate,表示不使用缓存副本,强制每次都向服务器重新验证资源;Pragma 是 HTTP/1.0 兼容字段,设置为 no-cache 同样表示不使用缓存;Expires 设置为 0,表示资源已过期,需要重新获取。

  1. Nginx 服务器
    在 Nginx 的配置文件(通常是 nginx.conf 或具体站点的配置文件)中添加以下配置:
nginx 复制代码
location ~* \.(js|css|png|jpg|gif)$ {
    add_header Cache-Control "no-cache, no-store, must-revalidate";
    add_header Pragma "no-cache";
    add_header Expires "0";
}

这样,当客户端请求这些类型的资源时,服务器会返回相应的头信息,指示客户端不缓存资源。

  1. Node.js 服务(使用 Express 框架为例)
    在 Express 应用中,可以在处理资源请求的路由中添加头信息设置:
javascript 复制代码
const express = require('express');
const app = express();

app.get('/your-resource-path/*.js', (req, res, next) => {
    res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.setHeader('Pragma', 'no-cache');
    res.setHeader('Expires', '0');
    next();
});

// 其他路由和中间件设置

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

上述代码针对以 .js 结尾的资源请求设置了不缓存的头信息,next() 函数用于继续处理请求,将资源返回给客户端。

前端设置(以 JavaScript 为例)

  1. XMLHttpRequest 对象
    在使用 XMLHttpRequest 进行网络请求时,可以在请求头中添加 Cache-Control 等字段来控制缓存:
javascript 复制代码
const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-resource-url', true);
xhr.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.setRequestHeader('Expires', '0');
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // 处理响应数据
    }
};
xhr.send();
  1. Fetch API
    使用 Fetch 进行网络请求时,可以通过设置 headers 选项来添加不缓存的头信息:
javascript 复制代码
fetch('your-resource-url', {
    method: 'GET',
    headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0'
    }
})
.then(response => {
    if (response.ok) {
        return response.text();
    }
    throw new Error('Network response was not ok');
})
.then(data => {
    // 处理响应数据
})
.catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
});

通过以上服务端和前端的设置方法,可以有效地强制网络请求的资源不被缓存,确保每次获取的都是最新的资源内容。

在浏览器中,例如chrome浏览器,打开开发者调试工具的network面板,选中Disable cache选项,也可以强制不缓存。

那么Disable cache做了哪些操作呢?

传送门《disable cache》

相关推荐
excel19 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
倔强青铜三20 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
excel20 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript