MrM*_*rMo 8 javascript caching reactjs localforage axios
由于某种原因axios-cache-adapter,没有缓存GET文件下载请求,我认为这是由于responseType: 'blob'axios 生成 src 所需的设置(因为我对不需要设置此字段的其他请求没有缓存问题)网址(根据这个答案):
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
};
Run Code Online (Sandbox Code Playgroud)
我们将非常感谢您的帮助。
@D-Money为我指明了正确的方向。因此,基本上v3 修复了不使用或axios-cache-adapter缓存请求的问题,但它目前仅在测试版中可用,因此您必须在此期间按如下方式安装:responseType blobarraybuffers
npm 安装 axios-cache-adapter@beta
然后,您必须通过在选项readHeaders: false,中进行设置来进行轻微调整,并将 axios 默认配置直接移动到 中,在我的例子中,这会导致以下净变化:axios-cache-adaptersetupsetup
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
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1505 次 |
| 最近记录: |