如何获得axios-cache-adapter缓存文件下载与responseType blob? &g



出于某种原因,axios-cache-adapter没有缓存GET请求的文件下载,我认为这是由于设置responseType: 'blob'(因为我没有对其他不需要设置此字段的请求进行缓存问题),这是axios生成src url所需的(根据此答案):

src: URL。createObjectURL(新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
};

非常感谢您的帮助。

@D-Money为我指明了正确的方向。所以基本上axios-cache-adapterv3修复了不缓存responseTypeblobarraybuffers请求的问题,但是它目前只在测试版中可用,所以你必须在过渡期间安装如下:

npm install axios-cache-adapter@beta

然后,您必须通过在setupaxios-cache-adapter选项中设置readHeaders: false,进行轻微调整,并将axios默认配置直接移动到setup中,在我的情况下,这会导致以下净更改:

const configureAxios = async () => {
await localforage.defineDriver(memoryDriver);
const forageStore = localforage.createInstance({
driver: [
localforage.INDEXEDDB,
localforage.LOCALSTORAGE,
memoryDriver._driver
],
name: 'my-cache'
});
return setup({
// Options passed to `axios.create()` method
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
// `axios-cache-adapter` options
cache: {
readHeaders: false,
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
};

最新更新