axios错误处理:
语法:在then方法的后面,通过点语法调用catch方法,传入回调函数并定义形参。
axios({
// 请求选项
}).then(result => {
// 处理数据
}).catch(error => {
// 错误处理
})
例如,注册用户的场景,如果用户已经存在,报错:

下面使用axios错误处理的语法,拿到错误信息,然后弹框提醒用户:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btn">注册用户</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 使用axios错误处理的语法,拿到错误信息,然后弹框提醒用户
document.querySelector('.btn').addEventListener('click', () => {
axios({
url: 'https://hmajax.itheima.net/api/register',
// 指定请求的方法
method: 'post',
// 提交数据
data: {
username: 'itheima787',
password: '123456'
}
}).then(result => {
// 成功的情况
console.log(result)
}).catch(error => {
// 失败
// 处理错误信息
console.log(error)
console.log(error.response.data.message)
alert(error.response.data.message)
})
})
</script>
</body>
</html>


57

被折叠的 条评论
为什么被折叠?



