(syntax)axios
2022-09-01 00:00:00

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
//GET GET方法传递参数 URL (/user?ID=12345) 和  params :{ } 传递参数 (传递参数的两种方式)
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){})
//POST
axios.post('').then().catch()
axios.post('/user',{ firstName:'',lastName:'' }).then().catch()
// 并发 axios.all
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'} //头信息
}
// post
axios({methods、url、data})
axios({
methods:'post',
url:'/user/12344',
data:{
firstName:'',
LastName:''
}
})
// get
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
}).then()
// 发送 GET 请求(默认的方法)
axios('/user/12345');

响应数据

1
2
3
4
5
6
7
8
9
10
11
12
{
// data 由服务器提供的响应 数据
data:{},
// status HTTP 状态码
status:200,
// statusTest 来自服务器响应的HTTP状态信息
statusText:"OK",
// headers 服务器响应的头信息
headers:{}
// config 是为请求提供的配置信息
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/xxx.interceptors.request/response.use()
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 () {});

// 移除拦截 axios.interceptors.request.eject(Interceptor)
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; }// 状态码范围
})

取消

  • cancel token 取消请求
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解析

  • ES
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,
});
  • Node
1
2
const querystring = require('querystring');  
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
上一页
2022-09-01 00:00:00
下一页