在带有VueJs的Axios中,当responseType为blob时,如何读取http错误? [英] How can I read http errors when responseType is blob in Axios with VueJs?

查看:567
本文介绍了在带有VueJs的Axios中,当responseType为blob时,如何读取http错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的VueJS应用程序中使用带有Axios的blob responseType来从服务器下载文档.当响应代码为200时,它可以正常工作并下载文件,但是当出现任何http错误时,发现错误时我无法读取状态代码,因为该错误是JSON响应.

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.

有人遇到过类似的问题,并且找到了一种将blob响应类型转换为json并根据状态码引发错误的方法吗?

我尝试从Laravel后端以纯文本格式发送响应,并尝试将响应转换为JSON或前端文本,但是没有运气.

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);
});

我只想根据状态代码抛出错误消息.如果它是401,只是希望它被未经授权而其他任何东西都扔到组件上.

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.

推荐答案

use err.response.status

     Axios ({ 
        url: 'xxxx', 
        method: 'GET', 
        responseType: 'blob', 
        }) 
    .then ((response) => { 
        // code pour lire la réponse et créer l'URL de l'objet avec le blob et télécharger le document 
    }) 
    .catch ((error) => { 
      console.log ('status', error.response.status); 
 ; 
 
});
    ```

这篇关于在带有VueJs的Axios中,当responseType为blob时,如何读取http错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆