1.安装
单独的文件
直接引入就可以
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
在vue项目中使用
安装插件
$ npm install axios --save
全局注册
import axios from ‘axios’
Vue.prototype.$axios = axios
然后就可以使用this.$axios获取
2.基本使用
1.方法1
axios.请求类型('接口路径',参数对象)
.then(function(res){})
.catch(function(req){})
2.方法2
axios(配置对象)
.then(function(res){})
.catch(function(req){})
具体配置什么稍后再说
3.并发请求
function foo1(){
return axios1...
}
function foo2(){
retuen axios2...
}
Peomise.all(foo1(),foo2())
3.请求配置
常用的配置如下
配置名 | 含义 |
---|---|
url | 请求接口 |
method | 请求类型 |
headers | 请求头 |
baseurl | 共同路径 |
pramas | 请求参数 |
timeout | 超时时间 |
4.实例化
实例化出不同的axios对象,分别设置不同的默认配置
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
5.默认配置
将所有请求通用的配置抽取出来,减少代码量
this.$axios.defaults.baseURL = 'https://api.example.com';
this.$axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
this.$axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
6.相应数据
请求成功后接口会返回一些数据
{
//由服务器提供的响应数据
data: {},
//来自服务器响应的 HTTP 状态码
status: 200,
//来自服务器响应的 HTTP 状态信息
statusText: 'OK',
//服务器响应头
headers: {},
//`axios` 请求的配置信息
config: {},
// `request` 是生成此响应的请求
request: {}
}
//这些数据都在then封装在函数中的对象内
7.拦截器
添加
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
});
移除
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);