Jag*_*ati 4 error-handling node.js reactjs axios
我在我的反应应用程序中有一个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);
})
Run Code Online (Sandbox Code Playgroud)
我能够成功记录成功请求的数据.但是,当我故意产生错误并尝试console.log时,我没有得到结果记录,我只是看到了
POST HTTP://本地主机:3000 /登录 401(未授权):3000 /登录:1
错误:请求失败,状态码401 login.js:66at createError(createError.js:16)
在定居(settle.js:18)
在XMLHttpRequest.handleLoad(xhr.js:77)
但是,当我在Chrome控制台中转到"网络标签"时,我会看到以下回复.
提前感谢您的帮助.
Shu*_*tri 18
来自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: {}
}
Run Code Online (Sandbox Code Playgroud)
所以基本上 catch(error => )只是catch(response => )
所以你可以记录error.response.data ,你应该能够看到你的回复消息.
当您记录时
console.log(error),您看到的是对象上方法string返回的内容.toStringerror
根据相同文档的错误处理部分,您可以捕获错误响应
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);
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6618 次 |
| 最近记录: |