在使用axios发送请求时,应该使用try-catch语句捕获可能出现的错误,并且在catch语句中处理该错误。
以下是示例代码:
try {
const response = await axios.get('http://some-api.com');
console.log(response.data);
} catch (error) {
if (error.response) {
// 请求成功,但服务器返回错误状态码
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求成功,但没有收到服务器响应
console.log(error.request);
} else {
// 发生了其他错误
console.log('Error', error.message);
}
}
这段代码将请求包装在一个try-catch块中,并检查错误对象的响应属性和请求属性以确定发生了什么错误。 这样,就可以在发生网络错误时得到更详细的错误信息。