鍍金池/ 問答/HTML/ axios 的responseType 類型動態(tài)設(shè)置

axios 的responseType 類型動態(tài)設(shè)置

axios請求下載導(dǎo)出一個文件,請求成功時返回的是一個流形式的文件,需要設(shè)置responseType: 'arraybuffer',但是請求失敗的時候返回的是json ,需要用默認(rèn)的responseType: 'json'來處理錯誤信息,那么問題來了,我該怎么根據(jù)服務(wù)器響應(yīng)后才設(shè)置這個responseType?

回答
編輯回答
獨(dú)特范

thank you , mark

2017年7月16日 11:32
編輯回答
落殤

同樣遇到這個問題,請問樓主后來怎么解決的呢

2018年9月18日 18:29
編輯回答
伴謊

請求設(shè)置了responseType: 'arraybuffer',
請求成功時,下載文件
請求失敗時,后端返回json對象,如:{"msg":"系統(tǒng)異常","code":1,"success":false},也被轉(zhuǎn)成了arraybuffer

我的解決方案是,失敗時,將數(shù)據(jù)arraybuffer轉(zhuǎn)成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' }) // 假設(shè)文件為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))) //轉(zhuǎn)化成json對象
          console.log(res)
      })
2018年5月2日 07:15
編輯回答
吃藕丑

難道 請求失敗返回的http 狀態(tài)碼也是 200??

2018年6月10日 05:04