当我们使用 responseType: "blob"
下载文件时,后台返回错误的 code 无法直接拦截,因为此时数据已经被包装成 blob,所以需要将 blob 转换为 json 解析。
FileReader 对象允许 Web 应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。
readAsText 方法可以将 Blob 或者 File 对象转根据特殊的编码格式转化为内容 (字符串形式)
具体代码如下,为 axios
响应拦截器中:
const res = response.data;
// 使用 responseType: "blob" 请求文件流时拦截报错信息
if (response.config.responseType === "blob") {
if (res.type === "application/json") {
const reader = new FileReader();
reader.readAsText(res, "utf-8");
reader.onload = function () {
const _res = JSON.parse(reader.result);
if (_res.code === 401) {
// 未登录弹窗
showLoginDialog();
}
};
return Promise.reject("error");
} else {
return response.data;
}
}