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:
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?