axios请求responseType设置为blob时,无法获取接口返回的异常提示

197 阅读1分钟
  • 异常情况:

image.png

  • 正常情况:

image.png

if ((response.status = 200)) {
      // 当响应type为'application/json'时,说明有异常,需要对异常做一些处理
      if (response.data.type === 'application/json') {
        // json信息展示
        const fileReader = new FileReader()
        fileReader.onload = function () {
          try {
            const jsonData = JSON.parse(fileReader.result) // 说明是普通对象数据,后台转换失败
            console.log('后台返回的信息', jsonData.status)
            notification.error({
              message: '下载失败',
              description: jsonData.status.msg
            })
          } catch (err) {
            // 解析成对象失败,说明是正常的文件流
            console.log('success...')
          }
        }
        fileReader.readAsText(response.data)
      } else {
        // 下载文件流
        console.log('下载文件流')
        const url = window.URL.createObjectURL(response.data)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        const date = moment().format('YYYYMMDD')
        const lastName = response.headers['content-disposition'].match(/.+\.([a-z|A-Z]+).*/)[1] // 获取后缀名
        console.log('lastName', lastName)
        link.setAttribute('download', `${date}${response.config.fileName}.${lastName}`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
    } else {
      notification.error({
        message: '下载失败',
        description: response.statusText
      })
    }