在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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

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

thank you , mark

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

同樣遇到這個(gè)問(wèn)題,請(qǐng)問(wèn)樓主后來(lái)怎么解決的呢

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

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

我的解決方案是,失敗時(shí),將數(shù)據(jù)arraybuffer轉(zhuǎn)成Json對(duì)象就好了。
舉個(gè)例:


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對(duì)象
          console.log(res)
      })
2018年5月2日 07:15
編輯回答
吃藕丑

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

2018年6月10日 05:04