返回博客

JS Axios 获取 Blob 类型响应中的 JSON 数据

使用 Axios 获取 Blob 类型响应数据并解析为 JSON 对象的方法,包括处理错误和非 JSON 数据的情况。文章提供了两种示例代码,并解释了如何判断响应数据是否为 JSON Blob,以及如何将其转换为 JSON 对象。

Mt.r
|

用 Axios 上传文件的几种方式

post("some/api/url", someDataForBackend, {
      responseType: "blob",
    })
      .then(async (response) => {
        const isJsonBlob = (data) => data instanceof Blob && data.type === "application/json";
        const responseData = isJsonBlob(response?.data) ? await (response?.data)?.text() : response?.data || {};
        const responseJson = (typeof responseData === "string") ? JSON.parse(responseData) : responseData;

        console.log(responseJson)
      });
axios.get(`/download/blob/api`, {
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  },
  validateStatus: (s) => s <= 500,
  responseType: 'blob',
}).then(async (res) => {
  if (res.status !== 200) {
    // error handling
    const error = JSON.parse(await res.data.text());
    console.log('error: ', error);
  } else {
    // success blob file
  }
});

后记