Skip to content

axios相关 #33

@CodeDreamfy

Description

@CodeDreamfy

自定义拦截器

当请求失败的时候进行二次请求

axios.defaults.retry = 2; // 在第一个失败的请求之后重试该请求的次数
axios.defaults.retryDelay = 1000;// 在失败的请求之间等待的毫秒数(默认为1)
instance.interceptors.response.use(undefined, (err) => {
  const { config } = err;
  // If config does not exist or the retry option is not set, reject
  if (!config || !config.retry) return Promise.reject(err);
  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;
  // Check if we've maxed out the total number of retries
  if (config.__retryCount >= config.retry) {
    // Reject with the error
    return Promise.reject(err);
  }
  // Increase the retry count
  config.__retryCount += 1;

  const backoff = new Promise(((resolve) => {
    setTimeout(() => {
      resolve();
    }, config.retryDelay || 1);
  }));
  // Return the promise in which recalls axios to retry the request
  return backoff.then(() => axios(config));
});

参考自:axios官方github的issue

使用axios下载文件

可以解决下载下来文件为txt的情况;

axios({
  method: 'get', // post
  url: `${baseUrl}/xxx`,  // 你自己的下载地址
  responseType: 'blob'     // responseType需要根据接口响应的数据类型去设置
}).then(res => {
  let blob = new Blob([res.data], {
    type: 'application/octet-stream'  // 下载的文件类型格式(二进制流,不知道下载文件类型可以设置为这个), 具体请查看HTTP Content-type 对照表
  })
  // 增加对IE的下载支持
  if(window.navigator.msSaveBlob) {
    try {
        window.navigator.msSaveBlob(blob, fileName);
      } catch (e) {
        console.log(e);
      }
  } else {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.id = 'downloadExcel';
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      const el = document.querySelector(`#${id}`);
      el.parentNode.removeChild(el);
      URL.revokeObjectURL(url); // 释放掉blob对象
  }
}

参考:

Metadata

Metadata

Assignees

No one assigned

    Labels

    axiosaxios相关vuevue 相关知识点技巧

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions