Node.js 无法捕获并记录来自axios请求的错误响应
我的react应用程序中有一个axios请求,对此我遵循 这是我的axios请求Node.js 无法捕获并记录来自axios请求的错误响应,node.js,reactjs,error-handling,axios,Node.js,Reactjs,Error Handling,Axios,我的react应用程序中有一个axios请求,对此我遵循 这是我的axios请求 axios.post(helper.getLoginApi(), data) .then((response) => { console.log(response); this.props.history.push(from.pathname) }) .catch((error)=> {
axios.post(helper.getLoginApi(), data)
.then((response) => {
console.log(response);
this.props.history.push(from.pathname)
})
.catch((error)=> {
console.log(error);
})
我能够成功记录成功请求的数据。但是,当我故意产生一个错误并尝试将其记录到console.log中时,我不会将结果记录下来,我只是看到了
邮政401(未经授权)
:3000/登录:1错误:请求失败,状态代码为401 login.js:66 在createError(createError.js:16) 结算时(结算js:18) 在XMLHttpRequest.handleLoad(xhr.js:77) 然而,当我进入Chrome控制台的网络选项卡时,我可以看到下面返回的响应 提前感谢您的帮助。来自。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=>)
因此,您可以记录error.response.data
,并且应该能够看到您的响应消息
当您记录console.log(error)
时,您看到的是字符串
由error
对象上的toString
方法返回
根据相同文档上的错误处理部分,您可以像下面这样捕获错误响应
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);
}
})
您是否尝试过将axios包装成
try{}catch(e){}
语句?您是否尝试过检查响应。状态内部然后?只是一些想法-我不知道为什么不会work@lumio,正如我在.then中所说,我能够成功地记录响应.data
,但不在.catch
块中即使我自己使用axios,我也不确定当状态不是2xx
时axios是否总是失败。你是否尝试过在中抛出错误,然后在响应时抛出错误。状态不是200?我还没有尝试过,一旦我尝试了@ShubhamKhatri发布的答案,如果它不起作用,我会这样做