How can I read http errors when responseType is blob in Axios with VueJs?

回眸只為那壹抹淺笑 提交于 2020-06-27 09:41:28

问题


I'm using blob responseType with Axios in my VueJS app for downloading a document from the server. When the response code is 200 it works fine and download the file but when there is any http error, I'm not able to read the status code when I catch the error because the error is a JSON response.

Has anyone had a similar issue and worked out a way to convert the blob response type to json and thrown an error based on the status code?

I have tried sending the response as a plain text from Laravel backend and tried converting the response to JSON or text in the front-end but no luck.

I have tried reading error response headers but no luck.

Axios({
        url: 'xxxx',
        method: 'GET',
        responseType: 'blob', 
        })
    .then((response) => {
        //code to read the response and create object url with the blob and download the document
    })
    .catch((error) => {
      console.log('Error', error.message); //nothing
      console.log('Error', error.error); //undefined
      console.log('Error', error.data); //undefined

      const blb    = new Blob([error], {type: "text/plain"});
      const reader = new FileReader();

      // This fires after the blob has been read/loaded.
      reader.addEventListener('loadend', (e) => {
        const text = e.srcElement.result;
        console.log(text);
      });
     // Start reading the blob as text.
     reader.readAsText(blb);
});

I just want to throw the error message based on the status code. If it's 401 just want it to be unauthorized and anything else throw it on to the component.

来源:https://stackoverflow.com/questions/56286368/how-can-i-read-http-errors-when-responsetype-is-blob-in-axios-with-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!