问题描述:当我们请求后端下载文件接口返回流的时候,当接口报错前端确无法获取后端返回错误信息,如果我们不进行处理是获取不到错误信息的,下面就是获取到错误信息的办法
解决方案:可以在请求拦截里,对下载接口进行统一处理,通过 FileReader 获取错误信息
let typeCount = {
type: "application/octet-stream",
};
let blob = new Blob([response.data],typeCount);
const fileReader = new FileReader()
fileReader.readAsText(blob,'utf-8')
if(!response.headers['Content-Disposition']) {//此处是和后端定义好的
fileReader.onload = function () {
console.log(JSON.parse(fileReader.result))
return message({
type: "error",
message: JSON.parse(fileReader.result).message
})
}
}
cookie.setCookie('file',JSON.stringify(response.data));
dowmFile(response);//下载文件
希望可以帮到你