我在我的反应应用程序中有一个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(未经授权) :3000 /登录:1个
错误:请求失败,状态码为401 login.js:66在createError(createError.js:16)
在定居时(sett.js:18)在XMLHttpRequest.handleLoad(xhr.js:77)
但是,当我在Chrome控制台中转到“网络标签”时,我会看到以下回复。
提前感谢您的帮助。
答案 0 :(得分:13)
来自 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
,并且您应该能够看到您的回复消息。
当您记录
console.log(error)
时,您看到的是string
由toString
对象上的error
方法返回。
根据相同文档的错误处理部分,您可以捕获错误响应,如
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);
}
})