沐若清辰
人生如茶,浓也好,淡也好,各有味道

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
    }
  },

  

posted on 2022-03-29 16:43  沐若清辰  阅读(1799)  评论(0编辑  收藏  举报