当前位置: 首页 > article >正文

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

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

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

  1. Apache 服务器
    .htaccess 文件中添加以下代码,可以针对特定类型的文件(如 JavaScript、CSS、图片等)设置不缓存:
<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 或具体站点的配置文件)中添加以下配置:
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 应用中,可以在处理资源请求的路由中添加头信息设置:
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 等字段来控制缓存:
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 选项来添加不缓存的头信息:
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》


http://www.kler.cn/a/564264.html

相关文章:

  • Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
  • C++11智能指针
  • Idea 中 Project Structure简介
  • 排序算法学习笔记
  • 笔记一:字符函数和字符串函数
  • 小白向-用python实现选择排序
  • 想知道两轮差速方形底盘 URDF 咋做,ROS2 配 Rviz 咋显示吗?看这里!
  • Eureka的缓存原理分析
  • AI顿悟之旅 - 1 - DeepSeek的训练方法为什么相比GPT-o1大幅度减少算力资源?
  • Paperless-ngx文档管理系统本地部署
  • YOLOv5白皮书-第Y1周:调用官方权重进行检测
  • 轮式机器人在复杂地形中如何选择合适的全局路径规划算法?
  • 一、IDE集成DeepSeek保姆级教学(安装篇)
  • GPT1 与 GPT2 的异同
  • 鸿蒙新版开发工具DevEco Studio不能新建模拟的解决方法
  • 介绍下pdf打印工具类 JasperPrint
  • 【LeetCode】148. 排序链表
  • Spark Streaming是如何实现实时大数据处理的
  • path.join和path.resolve说明
  • Redis主从架构+使用sentinel实现主从架构高可用