关于axios 的responseType类型的设置

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))
      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 => {
    var enc = new TextDecoder('utf-8') var res = JSON.parse(enc.decode(new Uint8Array(err.data))) //转化成json对象 console.log(res) } )

  

posted on 2019-07-02 22:07  鲁班快跑  阅读(47682)  评论(3编辑  收藏  举报