Skip to content

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

Published: at 04:50 PMSuggest Changes

用 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
  }
});

后记


Previous Post
微信小程序 JS 添加自定义位置水印
Next Post
Mac 系统下快速删除 node_modules 文件夹