Dynamic setting of responseType type of axios

axios requests to download and export a file. If the request succeeds, it returns a file in stream form. You need to set responseType: "arraybuffer", but when the request fails, you return json, and you need to use the default responseType:" json" to handle the error message. So the question is, how should I set this responseType? according to the server response

Jun.17,2021

request set responseType: 'arraybuffer',
when the request succeeds, and when the request for downloading the file
fails, the backend returns a json object, such as {"msg": "system exception", "code": 1, "success": false}, which is also converted to arraybuffer

.

my solution is to convert the data arraybuffer into a Json object when it fails.
for example:

 

first understand the priority of the axios attribute configuration,

Let's go from low priority to high priority

  • let instance = axios.create ()
  • instance.defaults.timeout = 2500
  • instance.get ("getcarline", {
    timeout:5000
  • )

})

process according to the value of http status Code

  • http status Code:200 sets responseType: "arraybuffer"
  • http status Code:500 set axios.defaults.responseType = 'json';
Menu