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

在前端开发中,要强制网络请求的资源不被缓存,可以通过设置 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》

相关推荐
lvbb663 分钟前
框架修改思路
前端·javascript·vue.js
树上有只程序猿5 分钟前
Java程序员需要掌握的技术
前端
雷渊8 分钟前
深入分析Spring的事务隔离级别及实现原理
java·后端·面试
从零开始学安卓9 分钟前
Kotlin(三) 协程
前端
阿镇吃橙子12 分钟前
一些手写及业务场景处理问题汇总
前端·算法·面试
庸俗今天不摸鱼13 分钟前
【万字总结】前端全方位性能优化指南(九)——FSP(First Screen Paint)像素级分析、RUM+合成监控、Lighthouse CI
前端·性能优化
爱写代码的小朋友13 分钟前
IP 地址规划中的子网划分:/18 网络容纳 64 个 C 段(/24)的原理与应用解析
网络·网络协议·tcp/ip
逆袭的小黄鸭13 分钟前
JavaScript:作用域与作用域链的底层逻辑
前端·javascript·面试
用户261245834016113 分钟前
vue2实现滚动条自动滚动
前端