【问题标题】:catching error body using axios post使用 axios post 捕获错误正文
【发布时间】:2017-12-14 12:41:40
【问题描述】:

我正在从我的后端代码发送一个状态代码 422,其中包含错误描述的响应正文。我正在使用 axios post 如下发布请求:

post: function(url, reqBody) {
    const request = axios({
        baseURL: config.apiUrl,
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': sessionStorage.getItem('token')
        },
        method: 'POST',
        data: reqBody,
        responseType: 'json'
    });
    return request
        .then((res) => {
            return res;
        })
        .catch((error) => {
            console.log(error);
            return error;
        })
}

问题是当后端返回错误代码 422 时,我捕获的错误对象没有关于响应正文的信息。有什么方法可以找回错误文本吗?

【问题讨论】:

    标签: javascript post axios


    【解决方案1】:

    我遇到了同样的问题,答案(根据 Axios >= 0.13)是专门检查error.response.data

    axios({
        ...
    }).then((response) => {
        ....
    }).catch((error) => {
        if( error.response ){
            console.log(error.response.data); // => the response payload 
        }
    });
    

    更多详情请见here

    【讨论】:

      【解决方案2】:

      AXIOS 错误响应的“主体”取决于请求的响应类型。

      如果您想了解有关此问题的完整详细信息,可以查看此博文:How to catch the body of an error in AXIOS

      总的来说,AXIOS 将根据错误返回 3 个不同的主体:

      1. 错误的请求,我们实际上在我们的请求中做错了什么(缺少参数,格式错误),即实际上并没有发送。发生这种情况时,我们可以使用error.message 访问信息。

        axios.get('wrongSetup')
        .then((response) => {})
        .catch((error) => {
            console.log(error.message);
        })
        
      2. 错误的网络请求:当我们尝试访问的服务器根本没有响应时,就会发生这种情况。这可能是由于服务器关闭或 URL 错误。 在这种情况下,我们可以使用error.request访问请求的信息。

        axios.get('network error')
        .then((response) => {})
        .catch((error) => {
            console.log(error.request );
        });
        
      3. 错误状态:这是最常见的请求。任何返回状态不是 200 的请求都可能发生这种情况。它可能是未经授权的、未找到的、内部错误等等。当这个错误发生时,我们可以通过访问下面sn-ps中指定的参数来掌握请求的信息。对于数据(如上所述),我们需要访问error.response.data

        axios.get('errorStatus')
        .then((response) => {})
        .catch((error) => { 
             console.log(error.response.data);  
             console.log(error.response.status);  
             console.log(error.response.headers); 
         })
        

      【讨论】:

      • This can happen with any request that returns with a status that is different than 200. 我想说的不是 2XX/3XX。
      • 不错的概述。但也许值得一提的是服务器可能会回答,但error.response 可能是undefined。如果我们的服务器发送 504(包括一些 HTML 数据),就会发生在我身上。我猜这是因为浏览器因 CORS 而阻塞?
      【解决方案3】:

      对于那些使用 await/async 和 Typescript 的人

      try {
          const response = await axios.post(url, body)
      } catch (error) {
          console.log(error.response.data);
      }
      

      【讨论】:

        【解决方案4】:

        对于本机反应,它对我有用

        api.METHOD('endPonit', body)
          .then(response => {
           //...
          })
          .catch (error => {
            const errorMessage = JSON.parse(error.request.response)
            console.log(errorMessage.message)
          })
        

        【讨论】:

          【解决方案5】:

          我们可以像@JoeTidee 所说的那样检查error.response.data。但是如果响应有效负载是 blob 类型?您可以使用以下代码获取错误响应正文。

          axios({
              ...
          }).then((response) => {
              ....
          }).catch(async (error) => {
              const response = error.response
              if(typeof response.data.text === function){
                  console.log(await response.data.text()); // => the response payload 
              } else {
                  console.log(response.data)
              }
          });
          

          【讨论】:

            【解决方案6】:

            我从后端返回一个字符串,但期望一个 json 作为响应类型。所以我需要返回一个对象而不是字符串,以便 axios 正确处理它。

            【讨论】:

              猜你喜欢
              • 2018-03-25
              • 2021-12-05
              • 1970-01-01
              • 2019-12-03
              • 2023-04-07
              • 2021-07-05
              • 2018-04-19
              • 2021-07-27
              相关资源
              最近更新 更多