axios设置instance.defaults.responseType = 'blob’请求下载导出一个文件,请求成功时返回的是一个流形式的文件,正常导出文件。但是请求失败的时候后端返回的是json ,不会处理错误信息,而是直接导出包含错误信息的文件。这样拿到data中的数据就只有size type 类型
例如
这种情况,通常在封装的axios中我们都是以后端返回的code值进行判断,因此就没有办法获取到后端返回的错误信息进行提示;
因此我们有俩个思路 要不给后端传instance.defaults.responseType = 'json’格式 然后请求成功之后将json格式转化成blob在进行导出,要不就是给后端传instance.defaults.responseType = 'blob’请求失败之后讲blob转化成json 格式, 我本人使用的是请求失败之后讲blob转化成json 格式;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | service.interceptors.response.use( /** * If you want to get http information such as headers or status * Please return response => response */ /** * Determine the request status by custom code * Here is just an example * You can also judge the status by HTTP Status Code */ response => { if (response.headers[ 'content-type' ] === 'application/json' ) { const res = response.data if (res.size) { // 针对导出excel失败之后的处理等 2022年3月29日 // 将blob转为json const reader = new FileReader() let parseObj = null reader.readAsText(response.data, 'utf-8' ) reader.onload = function () { parseObj = JSON.parse(reader.result) Message.error(parseObj.message || 'Error' ) } return Promise.reject( new Error(res.message || 'Error' )) } else { if (res.code !== '200' ) { // Message({ // message: res.message || 'Error', // type: 'error', // duration: 5 * 1000 // }) Message.error(res.message || 'Error' ) // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // to re-login MessageBox.confirm( 'You have been logged out, you can cancel to stay on this page, or log in again' , 'Confirm logout' , { confirmButtonText: 'Re-Login' , cancelButtonText: 'Cancel' , type: 'warning' }).then(() => { store.dispatch( 'user/resetToken' ).then(() => { location.reload() }) }) } return Promise.reject( new Error(res.message || 'Error' )) } else { return res } } } else { return response } }, |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~