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

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

相关推荐
超级大只老咪3 分钟前
字段行居中(HTML基础语法)
前端·css·html
IT_陈寒16 分钟前
Python开发者必看!10个高效数据处理技巧让你的Pandas代码提速300%
前端·人工智能·后端
只_只33 分钟前
npm install sqlite3时报错解决
前端·npm·node.js
FuckPatience37 分钟前
Vue ASP.Net Core WebApi 前后端传参
前端·javascript·vue.js
南北是北北38 分钟前
类型推断、重载与桥方法
面试
数字冰雹38 分钟前
图观 流渲染打包服务器
服务器·前端·github·数据可视化
阿湯哥39 分钟前
Redis数据库隔离业务缓存对查询性能的影响分析
数据库·redis·缓存
JarvanMo40 分钟前
Flutter:我在网上看到了一个超炫的动画边框,于是我在 Flutter 里把它实现了出来
前端
麦兜*40 分钟前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
2503_9248068540 分钟前
海外IP的适用业务范围
网络·网络协议·tcp/ip