axios
superfast
基于Promise的HTTP库 可以用在浏览器和Node.js
1 2 3
| // axios npm i axios yarn add axios
|
1 2 3 4 5 6 7 8 9
| // vue-axios npm install --save axios vue-axios
import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios) // Vue.axios == axios == this.axios == this.$http axios/Vue.axios/this.axios/this.$http.get('xxx').then(()=>{}).catch(()=>{})
|
API
- axios.xxx 请求方法的别名
- .then((response) => {}) 数据处理部分
- .catch((error) =>{}) 错误处理部分
- 请求方法别名
axios.xxx
- request(config) 请求方法提供了别名、可以直接使用别名来发起请求
- get、delete、head、option(url[, config])
- post、put、patch(url[, data[, config]])
- 并发
- all([fuc(),fuc()]) [] 数组
- spread(callback) 回调函数
- 创建实例 create()
- axios({config})
- config:
- method url data:{ key:value } params:{} timeout: 1000 responseType:’xxx’ proxy:{} auth: { } //
Authorization
头
- .then((response) => {}) 数据处理部分
- .catch((error) =>{}) 错误处理部分
功能
- 默认值 axios/instance.defaults.xxx = xx create({ baseURL:xxx })
- baseURL headers.common[‘Authorization’]= AUTH_TOKEN headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’
- 超时 xxx.defaults.timeout = 1000 create({ timeout:1000 })
- 拦截器
- 添加拦截 axios/xxx.interceptors.request/response.use() const xxx = axios.create()
- 移除拦截 axios.interceptors.request.eject(Interceptor)
- 错误处理 if (error.response == 200) {} else if(){ } validateStatus:(status) =>{ return status < 500 }
- 取消请求 axios.CancelToken.source() cancelToken: source.token source.cancel(‘xxx’);
- JSON解析 ES6:qs.stringify(data) Node:querystring.stringify({ foo: ‘bar’ }
axios.xxx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| v-for=msg {{ msg.item }}
data(){ msg:[] } mounted(){ axios.get('url') .then(response => { this.msg = response.data }) .catch(error => { error }) } axios.get('/user?ID=12345').then().catch() axios.get('/user', { params: { ID: 12345 } }).then(function(response){}).catch(function(error){})
axios.post('').then().catch() axios.post('/user',{ firstName:'',lastName:'' }).then().catch()
axios.all([fuc1(),fuc2()]).then()
|
axios({})
axios({methods、url、data}).then().catch()
axios({ }) 或 axios('')
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
| axios.create([config]) const instance = axios.create({ baseURL = '', timeout:1000, headers: {'X-Custom-Header': 'foobar'} }
axios({methods、url、data}) axios({ methods:'post', url:'/user/12344', data:{ firstName:'', LastName:'' } })
axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }).then()
axios('/user/12345');
|
响应数据
1 2 3 4 5 6 7 8 9 10 11 12
| { data:{}, status:200, statusText:"OK", headers:{} config:{} }
|
配置默认值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const instance = axios.create({ baseURL: 'https://api.example.com' timeout: 1000 }); instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
var instance = axios.create() instance.default.timeout = 1000 instance.get('/longRequest', { timeout: 5000 });
|
拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); });
axios.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); });
const instance = axios.create(); instance.interceptors.request.use(function () {});
const myInterceptor = axios.interceptors.request.use(function () {}); axios.interceptors.request.eject(myInterceptor);
|
错误处理
1 2 3 4
| axios.get('').catch((error) =>{ if (error.response) {}else if(){} else{ } validateStatus: function (status) { return status < 500; } })
|
取消
1 2 3 4
| const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('',{ cancelToken: source.token }) source.cancel('Operation canceled by the user.');
|
JSON解析
1 2 3 4 5 6 7 8
| import qs from 'qs'; const options = axios({ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify({ 'bar': 123 }), url, });
|
1 2
| const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
|