如何让 axios-cache-adapter 缓存带有 responseType blob 的文件下载?

How to get axios-cache-adapter to cache file downloads with responseType blob?

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

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
};

非常感谢您的帮助。

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

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
};