Axios 同时支持下载和 JSON 数据格式

1,817 阅读1分钟

一、需求

后端导入Excel之后,以Excel的方式反馈每一条处理的结果,但有时可能上传的文件错误或者权限限制的错误提示,需要返回json数据

二、问题

若设置 Axios 的responseType为 blob,只能接收Excel文件,json数据没法处理

三、解决方案

Axios 发送请求指定为 responseType 为 arraybuffer

  • 若 Response 的 Content-Type 为 application/json,则先将返回的数据转换成字符串,然后再转换为 JSON 。

  • 若 Response 的 Content-Type 为 application/vnd.ms-excel,则下载Excel

if (response.headers['content-type'].indexOf('application/json') > -1) {
   const result = JSON.parse(Buffer.from(response.data).toString('utf8'))
} else if (response.headers['content-type'].indexOf('application/vnd.ms-excel') > -1) {
    window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
}