I have the following axios
call which is failing because of authorization issue. Hence, I want to display a message (maybe growl) on the screen once control reaches catch
block. I can see the response payload in the Network tab but it’s not showing up when I am printing err.response
as shown in the code below. The response payload shown in the browser looks like the following:
How can I grab the Response Payload
value starting with NOT AUTHORIZED: ....
inside catch
block of axios?
const currentDate = new Date()
let deliverDate = getFormattedDate(currentDate);
const data = {
downloadType: '1',
dataDeliveryPojo: {
id: '0',
deliveredBy: JSON.parse(sessionStorage.getItem('loggedInUser')).personId,
deliveredToPersonId: JSON.parse(sessionStorage.getItem('loggedInUser')).personId,
deliverDate: deliverDate,
purposeId: 10,
companyId: 1234,
personId:JSON.parse(sessionStorage.getItem('loggedInUser')).personId
},
};
/*
The response.data returned from Axios is a JSON string. So creating a Blob from that JSON doesn't produce the correct object.
Hence, make sure to tell axios to return blob
From the Axios docs:
// responseType indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType: 'json', // default
*/
axios.post('api/fileDownload',
data,
{responseType :'blob'}
).then((blob) => {
let fileName = "";
let disposition = blob.headers['content-disposition'];
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
let matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
const url = window.URL.createObjectURL(blob.data);
const a = document.createElement('a');
a.href = url;
a.download = fileName
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}).catch((err) => {
console.log("Am I landing in catch block?");
console.log(err.response);
})
The output of console.log(err.response);
in the console is:
{
"data": {},
"status": 401,
"statusText": "",
"headers": {
"cache-control": "no-cache, no-store, must-revalidate",
"content-length": "84",
"content-type": "text/plain; charset=UTF-8",
"expires": "0",
"pragma": "no-cache"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8"
},
"baseURL": "https://myserver.com/MyServices/",
"method": "post",
"responseType": "blob",
"url": "https://myserver.com/MyServices/api/fileDownload",
"data": "{\"downloadType\":\"1\",\"dataDeliveryPojo\":{\"id\":\"0\",\"deliveredBy\":\"TAN\",\"deliveredToPersonId\":\"TAN\",\"deliverDate\":\"2021-06-11\",\"purposeId\":10,\"companyId\":1234,\"personId\":\"TAN\"}}"
},
"request": {}
}