I wanted to include some error information in my app but I am having trouble parsing the response. I am sending a POST request using axios to a remote server to transfer some file like this.
//http is an axios instance
const response = await http.post(url, formData, {
headers: {
'content-type': 'multipart/form-data',
},
});
if (response) {
return { errors: false };
} else {
return {
errors: true,
errorMessages: ['There was an error uploading the file'],
//i want to extract errors array from response actually
};
}
I can upload my file just fine and the backend seems to be validating everything as expected. So when I try to force errors sending invalid files, I see a response is coming back from the backend in the network tab of devtools that looks like this:
{"hasErrors":true,"data":false,"errors":["file extension validation: File must use .xlsx extension."]}
But in my front I can't access neither of those fields in my response variable. The server is responding with code 400.
I appreciate any help as I'm kinda lost trying to log this and don't want to show just a generic error message when server is actually providing this information.
The trouble here is that axios doesn't resolve post calls with 400-status responses; it throws an error that you can catch.
try {
const response = await http.post(/* your config */);
return {errors: false};
} catch (e) {
const {response} = e;
return {errors: true};
}