专注网络数据请求的库,比jquery更轻量,比xhr更简单好用

post 请求

1
2
3
4
5
axios.get('url',{params:{/*参数*/}}).then(function(res){
var result = res.data; // res.data才是服务器返回的数据
console.log(result)
})
// 参数转换成了查询字符串

post请求

1
2
3
4
5
axios.post('url',{/*参数*/}).then(function(res){
var result = res.data;
console.log(result)
})
// 参数默认转换成json

axois 请求

1
2
3
4
5
6
7
axios({
method: '请求类型',
url: '请求的URL地址',
headers: {Authorization:'Bearer '+token} // 带上token的请求头
data: { /* POST数据 */ }, // post传参,put传参
params: { /* GET参数 */ } // get传参,delete传参
}).then(callback)

axios全局配置

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.timeout = 2500;
// 配置公共的请求头
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// 配置公共的 post 的 Content‐Type
axios.defaults.headers.post['Content‐Type'] = 'application/x‐www‐form‐urlencoded';



// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],

axios 拦截器

  • 请求拦截器
    请求拦截器的作用是在请求发送前进行一些操作
    例如在每个请求体里加上token,统一做了处理如果以后要改也非常容易

  • 响应拦截器
    响应拦截器的作用是在接收到响应后进行一些操作
    例如在服务器返回登录状态失效,需要重新登录的时候,跳转到登录页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 1. 请求拦截器
axios.interceptors.request.use(function(config) {
console.log(config.url)
// 1.1 任何请求都会经过这一步 在发送请求之前做些什么
config.headers.mytoken = 'nihao';
// 1.2 这里一定要return 否则配置不成功
return config;
}, function(err){
//1.3 对请求错误做点什么
console.log(err)
})

//2. 响应拦截器
axios.interceptors.response.use(function(res) {
//2.1 在接收响应做些什么
var data = res.data;
return data;
}, function(err){
//2.2 对响应错误做点什么
console.log(err)
})