axios请求缓存+防止重复提交
分类专栏: Javascript&
简介 前端实现api接口缓存。
<pre>import axios from 'axios'
// 数据存储
export const cache = {
data: {},
set (key, data) {
this.data[key] = data
},
get (key) {
return this.data[key]
},
clear (key) {
delete this.data[key]
}
}
// 建立唯一的key值
export const buildUniqueUrl = (url, method, params = {}, data = {}) => {
const paramStr = (obj) => {
if (toString.call(obj) === '[object Object]') {
return JSON.stringify(Object.keys(obj).sort().reduce((result, key) => {
result[key] = obj[key]
return result
}, {}))
} else {
return JSON.stringify(obj)
}
}
url += `?${paramStr(params)}&${paramStr(data)}&${method}`
return url
}
// 防止重复请求
export default (options = {}) => async config => {
const defaultOptions = {
time: 0, // 设置为0,不清除缓存
...options
}
const index = buildUniqueUrl(config.url,config.method,config.params,config.data)
let responsePromise = cache.get(index)
if (!responsePromise) {
responsePromise = (async () => {
try {
const response = await axios.defaults.adapter(config)
return Promise.resolve(response)
} catch (reason) {
cache.clear(index)
return Promise.reject(reason)
}
})()
cache.set(index, responsePromise)
if (defaultOptions.time !== 0) {
setTimeout(() => {
cache.clear(index)
}, defaultOptions.time)
}
}
return responsePromise.then(data => JSON.parse(JSON.stringify(data))) // 为防止数据源污染
}
例子:
import axios from 'axios'
import cache from './cache'
// get请求
export async function getData (payload) {
return axios.get('/path', {
params: payload,
adapter: cache({
time: 0
})
})
}
// post请求
export async function postData (payload) {
return axios.post('/path', payload, {
adapter: cache({
time: 1000
})
})
}
</pre>
分享到:
转载:
https://segmentfault.com/a/1190000013167994
喜欢 1
收藏
暂无评论信息
- 相关文章
- 文章推荐
-
Docker 常用命令
docker目前代替虚拟机使用的一个容器,灵活好用。
-
娱美德旗下MMORPG手游《传奇4》将推出新PVP玩法"比奇掠夺"&
《传奇4》推出新门派PVP玩法!韩国首尔2022年6月29日 /美通社/ -- 《传奇4》(MIR4)的新PVP玩法比奇掠夺(Bicheon Heist)于2022年6月28日推出。
-
git:如何管理本机的多个ssh密钥(多个远程仓库账号)
如果我们电脑上已经存在了一个ssh key,那么我们需要在我们电脑上生成第二个你想在本电脑上使用的id_rsa,使用命令:ssh-keygen -t rsa -C "你的github账号"。
-
docker搭建jenkins环境执行宿主机的docker无权限的解决方法
初次搭建jenkins持续集成工具的时候,在运行项目阶段出现 permission denied的情况
- 点击排行
- 站长推荐
- 猜你喜欢
- 网站信息
- 站内问答:12篇
- 站内文章:203篇
- 建站时间:已运行798天
- 备案号: 浙ICP备2022018799号
- 语言:
English(USA)
French(FR)
Chinese(ZH)
无数据