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 格式;
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 } },