Axios
特性
- 支持node端和浏览器端
- promise
- 丰富的配置项
- transformRequest
- transformResponse
- baseURL
- 拦截器
- …
- 社区庞大
安装
npm i axios
使用
npm
// 哪个地方用得到就在哪个组件引入
import Axios from 'axios'
CDN
常用方法
基本用法
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
get
axios.get('/user', {
params: {
ID: 12345
}
})
post
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
All
多个请求,全部成功了,才算成功;有一个失败了,就算失败了
// 第一个接口
function getCnode() {
return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
// 并发请求
Axios.all([getCnode(), getMall()])
.then( (res1, res2) => {
// 两个请求现在都执行完成
console.log(res1)
console.log(res2)
}))
.catch(err => {
console.log(err)
})
Race - 赛跑,比谁跑得快
多个接口,只要有一个成功了,就算成功
// 第一个接口
function getCnode() {
return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
// 并发请求
Axios.race([getCnode(), getMall()])
.then(( (res1, res2) => {
// 两个请求现在都执行完成
console.log(res1)
console.log(res2)
}))
.catch(err => {
console.log(err)
})
Spread() - 处理并发请求的便于取值的函数
// 第一个接口
function getCnode() {
return Axios.get('https://cnodejs.org/api/v1/topics111');
}
// 第二个接口
function getMall() {
return Axios.get('https://api.it120.cc/small4/shop/goods/category/all');
}
// 并发请求
Axios.all([getCnode(), getMall()])
.then(Axios.spread(function (res1, res2) {
// 两个请求现在都执行完成
console.log(res1)
console.log(res2)
}))
.catch(err => {
console.log(err)
})
拦截器
拦截器,顾名思义,用来拦截什么东西的
在Axios中拦截器是用来拦截ajax请求的
分两组共有四个拦截点
-
request
成功
失败 -
response
成功 失败
实战案例 - loading动画
// App.vue
<template>
<div style="position: fixed; top: 0; left: 0; background: orange; opacity: 0.5; width: 100%; height: 1000px; text-align:center; padding-top: 420px; font-size: 100px;" v-show="isLoading">Loading...</div>
</template>
export default {
data() {
return {
isLoading: true // 默认显示
}
},
created () {
// 添加响应拦截器
Axios.interceptors.response.use( (response) => {
// 对响应数据做点什么
this.isLoading = false // 数据请求成功isloading改为false,loading隐藏掉
return response;
});
}
}