虽然前端频繁请求不是很好,但是有些需求也是没办法。今天说下前端怎么处理请求优化
1.通过setTimeout来缓解请求频率
2.设置无缓存
html文件设置meta头部
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate">
接口请求时设置header头
headers: {'Cache-Control': 'no-store' }
3.axios可通过CancelToken,将在pending的接口去掉
import axios from "axios";
var CancelToken = axios.CancelToken;
var cancel
// 取消上一次请求
cancelRequest()
http.request({ url: url,headers: {'Cache-Control': 'no-store' },method: "post",data:{},cancelToken: new axios.CancelToken((c) => {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})})
.then(async(res: any) => {
})
.catch(async(err: any) => {
if (axios.isCancel(err)) {
// 请求如果被取消
}
});
cancelRequest 取消请求方法
function cancelRequest () {
if (typeof cancel === 'function') {
cancel()
}
}
4.接口url添加事件戳
let url = '/xxx' + '?' + new Date().getTime();
5.可尝试使用tcp,udp,http2,http3,需要后端配合使用