Axios是一个js框架,用于发送ajax请求。
一、导入
// node中,使用npm安装
npm install axios
// HTML中,使用cdn安装
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、基本使用
// 使用axios为给定ID的user创建请求
// 请求成功,执行.then()中的内容,请求失败,执行.catch()中的内容
// res 、 err 为回调函数axios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(error)){console.log(error);});// 开发时的写法axios.get()
.then( res =>{} )
.catch( err =>{} )
// 基本使用axios.get('接口')// res:是axios库对响应数据做的一层包装
.then(res => {// 内容
})//不是业务逻辑出错,而是网络出错:1、url错误 2、网络错误
.catch(err => {// 内容
})// 本次请求完成,无论是否成功执行,都会执行此条内容
.then( ()=>{// 内容
} )
三、axios发送get和post
// get请求
axios.get(url:'')
.then( res =>{// 内容
})
.catch( error =>{// 内容
})// post请求
axios.post(url:'',{ // 参数列表 })
.then( res =>{} )
.catch( err => {} )
常用语法:
// 通过向axios传递响应的配置创建请求axios({method:'get/post',url:''// post发送请求,参数使用data进行传递data:{},// get发送请求,参数使用params进行传递params:{}
}).then( res=>{} ).catch()
四、链式语法
1、链式语法:对象可以连续调用
axios.get().then().catch()