2017-07-10 45 views
1

我从包含错误描述的响应主体的后端代码发送状态代码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,我赶上了错误的对象没有关于响应主体的信息。有什么办法可以检索错误文本吗?

回答

0

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

2

我有同样的问题和答案(按照爱可信> = 0.13)是专门检查error.response.data

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

详情请参阅here