无法捕获并logging来自axios请求的错误响应

我在我的应用程序中有一个axios请求,为此我遵循axios npm文档。

这是我的axios请求

axios.post(helper.getLoginApi(), data) .then((response) => { console.log(response); this.props.history.push(from.pathname) }) .catch((error)=> { console.log(error); }) 

我能够成功地在成功的请求上logging数据。 然而,当我故意产生一个错误,并尝试console.log它,我没有得到logging的结果,而我只是看到

POST http:// localhost:3000 / login 401(Unauthorized):3000 / login:1
错误:请求失败,状态码为401 login.js:66

在createError(createError.js:16)

在定居(定居点:18)

在XMLHttpRequest.handleLoad(xhr.js:77)

但是,当我在Chrome控制台中转到“networking”标签时,我可以看到下面的回复。

在这里输入图像描述

提前感谢您的帮助。

Github Docs 。 axios请求的响应看起来像

 { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} } 

所以本质上catch(error => )实际上就是catch(response => )

所以你可以loggingerror.response.data ,你应该能够看到你的回复消息。

当您loggingconsole.log(error) ,您看到的是error对象上的toString方法返回的string

根据同一文档中的error handling部分,您可以捕获错误响应

 axios.post(helper.getLoginApi(), data) .then((response) => { console.log(response); this.props.history.push(from.pathname) }) .catch((error)=> { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } })