在 axios 请求布尔值期间,参数的值是否传递给 catch 方法 ("error") 的回调?



我是新手。在axios get请求期间,我对catch方法的回调中参数的值感到困惑。为了清楚起见,下面是我试图弄清楚axios request背后的概念的代码片段。

axios.get('https://jsonplaceholder.typicode.com/posts')

.then(responce => {
console.log(responce)
this.setState(
{posts : responce.data}
)
})
.catch(error => console.log(error))
}

error参数是一个对象,它包含有关失败请求的信息,以便您可以适当地处理它,例如响应代码(EG 200、404、500(、服务器返回的任何响应数据以及响应上的标头。以下内容可以在axios文档中找到,用于处理错误:

axios.get('/user/12345')
.catch(function (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);
}
console.log(error.config);
});

注意上面代码中的注释,因为它们解释了在发出请求时由于错误而导致的不同情况下错误对象包含的内容。

如果您想查看有关HTTP错误的更多信息,也可以在文档中对该错误使用toJSON()方法。

axios.get('/user/12345')
.catch(function (error) {
console.log(error.toJSON());
});