【发布时间】:2021-11-03 02:26:28
【问题描述】:
由于某种原因,axios-cache-adapter 没有缓存 GET 文件下载请求,我认为这是由于设置了responseType: 'blob'(因为我在其他不需要设置此字段的请求上没有缓存问题因此)这是 axios 生成 src url 所必需的(根据this answer):
src: URL.createObjectURL(new Blob([response.data])),
我的适配器设置如下:
// set axios defaults
axios.defaults.headers.common = {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
};
const configureAxios = async () => {
await localforage.defineDriver(memoryDriver);
const forageStore = localforage.createInstance({
driver: [
localforage.INDEXEDDB,
localforage.LOCALSTORAGE,
memoryDriver._driver
],
name: 'my-cache'
});
return setup({
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000,
exclude: {
query: false
},
store: forageStore,
}
});
};
// call this function in JSX Component to download file
export const downloadFile = async (fileId) => {
const api = await configureAxios();
const response = await api.get(`api/download/${fileId}`, {
responseType: 'blob',
});
return response.data; // returns file data
};
非常感谢您的帮助。
【问题讨论】:
-
据包维护者之一,caching binaries is disabled。看起来有一个 PR 可以启用此功能,即still pending
-
@D-Money 我明白了,谢谢你,知道如何克服我的困境吗?
-
在这种情况下,我认为您等待更新的唯一选择是分叉
axios-cache-adapterrepo,自己进行更改,然后在项目中安装您的版本而不是原始版本。这当然意味着您不会收到对该软件包的任何更新,除非您手动更新您的分叉版本以获取它们。但作为一个临时解决方案,它会起作用
标签: javascript reactjs caching axios localforage