momo's Blog.

axios基本用法

字数统计: 568阅读时长: 2 min
2020/08/15 Share

1. axios 基本特性

axios 官网: https://github.com/axios/axios

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
axios.delete('http://localhost:8000/depart/3', {
params: {
id: 2
}
}).then(function (ret){
// data熟悉是固定的写法,用于获取后台的实际数据
console.log(ret.data)
})

axios.put('http://localhost:8000/depart/3', {
params: {
id: 2
}
}).then(function (ret){
// data熟悉是固定的写法,用于获取后台的实际数据
console.log(ret.data)
})

axios.get('http://localhost:8000/depart/').then(function (ret){
// data熟悉是固定的写法,用于获取后台的实际数据
console.log(ret.data)
})

1.1 GET传递参数

  • 通过 URL 传递参数
  • 通过params 选项传递参数
1
2
3
4
5
6
7
8
9
10
11
12
13
axios.get('http://localhost:8000/depart?id=123').then(function (ret){
// 通过URL传参
console.log(ret.data)
})

axios.get('http://localhost:8000/depart', {
params: {
id: 2
}
}).then(function (ret){
// 通过params传参
console.log(ret.data)
})

其他传参方式与GET请求无太大差异,请参考上面代码段

2. axios 全局配置

  • axios.defaults.timeout = 3000; //超时时间
  • axios.defaults.baseURL = ‘http://localhost:8000/'; // 默认地址
  • axios.defaults.headers[‘mytoken’] = ‘123123asdawdaw’ // 设置请求头

3. axios 拦截器

3.1 请求拦截器

在请求发送之前设置一些信息

1
2
3
4
5
6
7
8
// 添加一个请求拦截器
axios.interceptors.request.use(function (config){
config.headers['mytoken'] = '123123asdawdaw' // 设置请求头
return config
}, function (err){
// 处理响应的错误信息
return Promise.reject(err)
})

3.2 响应拦截器

1
2
3
4
5
6
7
axios.interceptors.response.use(function (res){
// 这里对返回的数据进行处理
return res;
}, function (err){
// 处理响应的错误信息
return Promise.reject(err)
})

4. async/await 的基本用法

  • async 关键字用于函数上(async函数的返回值是Promise实例对象)
  • await 关键字用于async函数当中 (await可以得到异步处理的结果)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async function queryData(){
let ret = await axios.get('http://localhost:8000/depart/2')
// 异步获取结果
console.log(ret)
}
queryData()

async function queryData(){
let ret = await axios.get('http://localhost:8000/depart/2')
// 异步获取结果
return ret
}

// 返回promise对象可调用then方法
queryData.then(ret => {
console.log(ret)
})

4.1 async/await 处理多个异步请求

1
2
3
4
5
6
7
8
9
10
11
async function queryData(){
let info = await axios.get('http://localhost:8000/depart/2')
let ret = await axios.get('http://localhost:8000/depart/2' + info.data)
// 异步获取结果
return ret
}

// 返回promise对象可调用then方法
queryData.then(ret => {
console.log(ret)
})
CATALOG
  1. 1. 1. axios 基本特性
    1. 1.1. 1.1 GET传递参数
  2. 2. 2. axios 全局配置
  3. 3. 3. axios 拦截器
    1. 3.1. 3.1 请求拦截器
    2. 3.2. 3.2 响应拦截器
  4. 4. 4. async/await 的基本用法
    1. 4.1. 4.1 async/await 处理多个异步请求