使用responseType: “blob“请求文件流时拦截报错信息

前言:下载文件的请求加了responseType: “blob”,当接口报错了如果不做处理则获取不到接口错误信息,此时下载的文件是有问题的。

// 模板下载
function getTemplateDown(fileName) {
  return request({
    url: `**/getTemplateDown`,
    method: "get",
    responseType: "blob",
  }).then(res => {
   	// 接口报错,下载失败
    if (res.type === 'application/json') {
      const reader = new FileReader();
      reader.readAsText(res, 'utf-8');
      reader.onload = function () {
        const _res = JSON.parse(reader.result);
        console.log(_res); // 此处为接口返回值
      }
    } else { // 正常下载
      const link = document.createElement("a");
      let blob = new Blob([res]);
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      link.setAttribute("download", `${fileName}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);  
    }
  });
}

你可能感兴趣的:(js,javascript,前端,js)