基于axios 的responseType类型的设置方法

responseType值的类型可为如下

基于axios 的responseType类型的设置方法

axios请求下载导出一个文件,请求成功时返回的是一个流形式的文件,需要设置responseType: \’arraybuffer\’,但是请求失败的需要返回的是json数据,

所以需要把arraybuffer转成Json对象。

例:

请求设置了responseType: \’arraybuffer\’,

请求成功时,下载文件,

请求失败时,后端返回json对象,如:{\”msg\”:\”系统异常\”,\”code\”:1,\”success\”:false},也被转成了arraybuffer

我的解决方案是,失败时,将数据arraybuffer转成Json对象就好了。

举个例:

api.downloadFile(params).then(res => {    
  if (res.status === 200 && res.data) {     
      var disposition = res.headers[\'content-disposition\']    
      var fileName = decodeURI(disposition.substring(disposition.indexOf(\'filename=\') + 9, disposition.length))<br>      let blob = new Blob([res.data], { type: \'application/pdf\' }) // 假设文件为pdf
     let link = document.createElement(\'a\')
     link.href = window.URL.createObjectURL(blob)
     link.download = fileName
     link.click()
     link.remove()
   } else {      // 其它情况
   }
  }).catch(err => {     <br>    var enc = new TextDecoder(\'utf-8\')
    var res = JSON.parse(enc.decode(new Uint8Array(err.data))) //转化成json对象
    console.log(res)
  }
)

以上这篇基于axios 的responseType类型的设置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容