gpt4 book ai didi

node.js - 无法捕获并记录来自 axios 请求的错误响应

转载 作者:搜寻专家 更新时间:2023-10-31 23:28:28 25 4
gpt4 key购买 nike

我在我的 React 应用程序中有一个 axios 请求,为此我正在关注 axios npm docs.

这是我的axios请求

 axios.post(helper.getLoginApi(), data)
.then((response) => {
console.log(response);

this.props.history.push(from.pathname)
})
.catch((error)=> {
console.log(error);
})

我能够在成功请求时成功记录数据。但是,当我故意产生错误并尝试对其进行 console.log 时,我没有记录结果,而是看到了

POST http://localhost:3000/login 401 (Unauthorized) :3000/login:1
Error: Request failed with status code 401 login.js:66

at createError (createError.js:16)

at settle (settle.js:18)

at XMLHttpRequest.handleLoad (xhr.js:77)

但是,当我转到 Chrome 控制台中的“网络”选项卡时,我可以看到返回了以下响应。

enter image description here

提前感谢您的帮助。

最佳答案

来自 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 => )

所以你可以记录error.response.data并且您应该能够看到您的回复消息。

When you log console.log(error), what you see is the string returned by the toString method on the error object.

根据同一文档的错误处理部分,您可以像这样捕获错误响应

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

关于node.js - 无法捕获并记录来自 axios 请求的错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44806333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com