Get json response from blob response type

See original GitHub issue

Describe the issue

Try to fetch blob by provided parameters - search attribute in POSTed data. Something error occurred on backend API and API return 400 JSON message. The browser recognize full message from API, because display it on Preview tab.

Example Code

Code snippet to illustrate your question

axios({
    method: 'post',
    url: '/some/route',
    responseType: 'blob',
    data: {
        search: 'random text'
    },
})
    .then((response) => {
        // handle success
    })
    .catch((error) => {
        console.log(error);

        // how to get Json response?
       //  error.response.data.message - not exists because of blob content
    })
    .finally(() => {
        // console.log('finish');
    });

API returned:

400: {"success":false,"uuid":"c034a1e5-0a27-4d68-a169-f0323000d0a7","message":"Some message."}

Expected behavior, if applicable

Get message/payload from axios in catch block if blob resposeType is expected and Json is returned.

Environment

  • Axios Version [e.g. 0.18.0]: 0.21.1
  • Adapter [e.g. XHR/HTTP]
  • Browser [e.g. Chrome, Safari]: all
  • Browser Version [e.g. 22]
  • Node.js Version [e.g. 13.0.1]: 15.14.0
  • OS: [e.g. iOS 12.1.0, OSX 10.13.4]
  • Additional Library Versions [e.g. React 16.7, React Native 0.58.0]

Additional context/Screenshots

.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

9reactions
DmitriyWebDevcommented, May 16, 2021

@LocalHeroPro

A possible solution.

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)
      });
7reactions
nichitaacommented, Dec 29, 2021

This worked for me.

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

Just check for status code and parse it to JSON if you know that the server may return a JSON error

Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I read http errors when responseType is blob in ...
The reason is that the response type is blob. In case of error, the status code is available directly in your exception object....
Read more >
Response.blob() - Web APIs - MDN Web Docs
The blob() method of the Response interface takes a Response stream and reads it to completion. It returns a promise that resolves with...
Read more >
AWS Amplify API, Blob Response Type(Binary Data) and Error ...
Learn how to use AWS Amplify API with Axios to query endpoints that return Blob response type but JSON error response type.
Read more >
JSON Blob | API
Upon successfully storing the JSON blob, a 201 response will be returned. The Location header in the response will be set to the...
Read more >
Blobs with HTTP Post and Angular 5 — A short story
Return <Blob> · The key here is to use responseType: 'blob' as 'json' instead of responseType: 'blob' . Refer to angular discussion on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found