2

In my react app, I am using the following approach to download a file using axios.

Approach 1:

axios.post('api/downloadMyFile', data, { responseType: 'blob' })
.then(blob=>{
  const url = window.URL.createObjectURL(blob.data); 
  const a = document.createElement('a');
  a.href = url;
  a.download = "download.zip"  
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(url);
})

Initially I was using this "Approach 2" but then had to change to "Approach 1" for the following reason:

The response.data returned from Axios is a JSON string. So creating a Blob from that JSON doesn't produce the correct object. More info on this is in my previous thread.

Approach 2:

axios.post('api/downloadMyFile',
    data
  ).then((response) => {

      console.log("Response testing ");
      console.log(response.data);

    }

The problem I am facing after switching to "Approach 1" is as follows:

In some case, webservice call can return NOT AUTHORIZED in the response.data. But since in "Approach 1" I am telling Axios to provide the response in the form of a Blob, all I see in console.log(blob) is the following:

enter image description here

Had I been using "Approach 2", and there was a scenario of NOT_AUTHORIZED, I would have seen something like this in console.log(response):

Object { data: "NOT_AUTHORIZED: you are not allowed to download this file", status: 200, statusText: "", headers: {…}, config: {…}, request: XMLHttpRequest }

Considering I am using approach 1, how can I access NOT_AUTHORIZED related information?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Tan
  • 1,433
  • 5
  • 27
  • 47

1 Answers1

0

backend should return a specific status code like 422 to mark that this response is not ok, and the extra info about the error is going to be sent in JSON.

on frontend side, you can try parse the response.data.text() to JSON, then read the errorCode or errorMessage to detect the detail reason why this file cannot be download.

Below is sample code that worked for me:

axios.post(`/tickets/download`, someFilterParams, {
  headers: {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  },
  responseType: 'blob',
}).then(async (res) => {
  if (res.status !== 200) {
    const errorAsJSON = JSON.parse(await res.data.text());
    console.log('error: ', errorAsJSON);
  } else {
    // save file
  }
});
hungnd
  • 91
  • 2
  • 4