一.安装
1.1、利用npm安装
1
| npm install axios --save
|
1.2、利用bower安装
1
| bower install axios --save
|
1.3、直接利用cdn引入
1
| <script src="https:// unpkg.com/axios/dist/axios.min.js"></script>
|
二.例子
2.1、发送一个 get 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| axios.get('/user?ID=12345') .then(function(response) { console.log(response); }) .catch(function(err) { console.log(err); });
axios.get('/user', { params:{ ID:12345 } }) .then(function(response) { console.log(response); }) .catch(function(err) { console.log(err); });
|
2.2、发送一个 post 请求
1 2 3 4 5 6 7 8 9 10
| axios.post('/user', { firstName:'Fred', lastName:'Flintstone' }) .then(function(res) { console.log(res); }) .catch(function(err) { console.log(err); });
|
2.3、一次性并发多个请求
1 2 3 4 5 6 7 8 9 10
| function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function(acct, perms){ }))
|
三.axios 的 API
3.1、axios可以通过配置 (config) 来发请求
3.1.1、axios(config)
1 2 3 4 5 6 7 8 9
| axios({ method:"POST", url:'/user/12345', data:{ firstName:"Fred", lastName:"Flintstone" } });
|
3.1.2、axios(url [,config])
3.2、请求方式的别名, 这里对所有已经支持的请求方式都提供了方便的别名
1 2 3 4 5 6 7 8 9 10 11 12 13
| axios.request(config);
axios.get(url[,config]);
axios.delete(url[,config]);
axios.head(url[,config]);
axios.post(url[,data[,config]]);
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])
|
注意:当我们在使用别名方法的时候,url, method, data这几个参数不需要在配置中声明
3.3、并发请求(concurrency), 即是帮助处理并发请求的辅助函数
1 2 3 4
| axios.all(iterable)
axios.spread(callback)
|
3.4、并发请求(concurrency),即是帮助处理并发请求的辅助函数
3.4.1、axios.create([config])
1 2 3 4 5
| var instance = axios.create({ baseURL:"https:// some-domain.com/api/", timeout:1000, headers: {'X-Custom-Header':'foobar'} });
|
3.4.2、实例的方法
以下是实例方法,注意已经定义的配置将和利用create创建的实例的配置合并
1 2 3 4 5 6 7 8 9 10 11 12 13
| axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])
|
四.请求的配置 (request config)
以下就是请求的配置选项,只有url选项是必须的,如果method选项未定义,那么它默认是以GET的方式发出请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| { url: '/user',
method: 'get'
baseURL: 'https:// some-domain.com/api/',
transformRequest: [function(data) { return data; }],
transformResponse: [function(data){ return data; }],
headers: {'X-Requested-With':'XMLHttpRequest'},
params: { ID: 12345 },
paramsSerializer: function(params) { return Qs.stringify(params,{arrayFormat:'brackets'}) },
data { firstName: "Fred" },
timeout: 1000,
withCredentials: false,
adapter: function(config){ },
auth: { username: "zhangsan", password: "s00sdkf" },
responseType: 'json', xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
onUploadProgress: function(progressEvent) {
}, onDownloadProgress: function(progressEvent) { },
maxContentLength:2000,
validateStatus:function(status){ return status >= 200 && status <300; },
maxRedirects: 5,
httpAgent: new http.Agent({keeyAlive:true}),
httpsAgent: new https.Agent({keeyAlive:true}),
proxy: { host:'127.0.0.1', port: 9000, auth: { username:'skda', password:'radsd' } },
cancelToken: new cancelToken(function(cancel) {
}) }
|
五.请求返回的内容
1 2 3 4 5 6 7
| { data: {}, status: 200, statusText: 'OK', // 从服务器返回的http状态文本 headers: {}, // 响应头信息 config: {} // `config`是在请求的时候的一些配置信息 }
|
你可以这样来获取响应信息
1 2 3 4 5 6 7 8
| axios.get('/user/12345') then(function(res){ console.log(res.data); console.log(res.status); console.log(res.statusText); console.log(res.headers); console.log(res.config); })
|
六.默认配置
你可以设置默认配置,对所有请求都有效
6.1、全局默认配置
1 2 3
| axios.defaults.baseURL = 'http:// api.exmple.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
|
6.2、自定义的实例默认设置
1 2 3 4 5 6 7
| var instance = axios.create({ baseURL: 'https:// api.example.com' });
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;
|
6.3、配置中的有优先级
1 2 3 4 5 6 7 8 9 10 11 12
|
var instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', { timeout: 5000 });
|
七.拦截器
你可以在请求、响应在到达then/catch之前拦截他们
7.1、添加一个请求拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| axios.interceptors.request.use(function(config) { return config; }, function(err) { return Promise.reject(error); });
axios.interceptors.response.use(function(res) { return res; }, function(err) { return Promise.reject(error); })
|
7.2、取消拦截器
1 2
| var myInterceptor = axios.interceptor.request.use(function() {}); axios.interceptors.request.eject(myInterceptor);
|
7.3、 给自定义的axios实例添加拦截器
1 2
| var instance = axios.create(); instance.interceptors.request.use(function() {});
|
八.错误处理
1 2 3 4 5 6 7 8 9 10 11 12 13
| axios.get('/user/12345') .catch(function(error){ if(error.response){ console.log(error.response.data); console.log(error.response.status); console.log(error.response.header); }else { console.log('Error',error.message); } console.log(error.config); });
|
九.取消
你可以通过一个cancel token来取消一个请求
你可以通过CancelToken.source工厂函数来创建一个cancel token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| var CancelToken = axios.CancelToken; var source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { } });
source.cance("操作被用户取消");
var cancelToken = axios.CancelToken; var cance; axios.get('/user/12345', { cancelToken: new CancelToken(function(c) { cancel = c; }) })
cancel();
|