如何从Axios中的http错误获取状态代码? [英] How can I get the status code from an http error in Axios?
本文介绍了如何从Axios中的http错误获取状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎很愚蠢,但是当Axios中的请求失败时,我正在尝试获取错误数据.
This may seem stupid, but I'm trying to get the error data when a request fails in Axios.
axios.get('foo.com')
.then((response) => {})
.catch((error) => {
console.log(error) //Logs a string: Error: Request failed with status code 404
})
是否可以获取一个带有状态码和内容的对象而不是字符串?例如:
Instead of the string, is it possible to get an object with perhaps the status code and content? For example:
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
推荐答案
您看到的是error
对象的toString
方法返回的字符串. (error
不是字符串.)
What you see is the string returned by the toString
method of the error
object. (error
is not a string.)
如果已从服务器收到响应,则error
对象将包含response
属性:
If a response has been received from the server, the error
object will contain the response
property:
axios.get('/foo')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
这篇关于如何从Axios中的http错误获取状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文