Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

axios相关 #33

Open
CodeDreamfy opened this issue Oct 12, 2019 · 0 comments
Open

axios相关 #33

CodeDreamfy opened this issue Oct 12, 2019 · 0 comments
Labels
axios axios相关 vue vue 相关知识点 技巧

Comments

@CodeDreamfy
Copy link
Owner

CodeDreamfy commented Oct 12, 2019

自定义拦截器

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

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对象
  }
}

参考:

@CodeDreamfy CodeDreamfy added vue vue 相关知识点 技巧 labels Oct 12, 2019
@CodeDreamfy CodeDreamfy changed the title axios拦截器 axios相关 Nov 8, 2019
@CodeDreamfy CodeDreamfy added the axios axios相关 label Nov 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
axios axios相关 vue vue 相关知识点 技巧
Projects
None yet
Development

No branches or pull requests

1 participant