【问题标题】:How to get axios-cache-adapter to cache file downloads with responseType blob?如何让 axios-cache-adapter 使用 responseType blob 缓存文件下载?
【发布时间】: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-adapter repo,自己进行更改,然后在项目中安装您的版本而不是原始版本。这当然意味着您不会收到对该软件包的任何更新,除非您手动更新您的分叉版本以获取它们。但作为一个临时解决方案,它会起作用

标签: javascript reactjs caching axios localforage


【解决方案1】:

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

npm install axios-cache-adapter@beta

然后您必须通过在setup 中的axios-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
};

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2020-06-12
    • 2021-04-12
    • 2017-06-15
    • 2018-01-08
    • 2019-04-10
    • 1970-01-01
    • 2021-09-22
    • 2018-04-25
    相关资源
    最近更新 更多