Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change responseType in Axios based on response

I've an axios request with responseType: 'arraybuffer' this works correctly when response is a success 200.

However when the api I'm accessing and returns a 500 with a json object - axios encodes that in an arraybuffer.

My current workaround is to use an arraybuffer-to-string library to decode the json error message. Is there a better way to do this? Prevent axios from converting response to the defined responseType?

I've tried response interceptors and there is also an open issue for axios to infer response types which would be great because if it saw application/json content-type and resolved it accordingly

like image 405
Alex Wachira Avatar asked Nov 09 '18 16:11

Alex Wachira


1 Answers

I just found the solution. In catch you can convert the arraybuffer response to json by this:

const data = await JSON.parse(new TextDecoder().decode(error.response.data));
like image 77
landsman Avatar answered Nov 09 '22 13:11

landsman