1.安装axios
1 | npm i axios |
2. axios的请求方式
2.1 get请求
2.1.1 axios.get方法
1 | //参数使用{ params:{} }方式,注意是{}内params:{} |
1 | // 简写方式,传递参数使用? |
2.1.2 axios()方法
注意:method为请求方法,当为get时使用params传递参数1
2
3
4
5
6
7
8
9axios({
method: 'get', //请求方法包含(get,post,delete,put)等
url: '/student', //请求路径
params: {name:'data1',age:'10'} //当method为get时的传参方式
}).then(res => { //then里面时请求成功的数据
console.log(res)
}).catch(err => { //当报错时走这里
console.error(err);
})
2.2 post 请求
2.2.1 axios.post(url,data)方法
注意:直接传递数据即可1
2
3
4
5
6
7
8
9
10//第一个参数为url,第二个参数为要传递的参数对象
axios.post("/student", {
name: "Lucy",
age: 10,
state: false,
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err);
})
2.2.2 axios()方法
1 | axios({ |
2.3 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
24axios({
//配置请求头
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
//method 默认为 GET [参数支持 GET POST DELETE HEAD OPTIONS PUT PATCH}
method: 'get',
url: '/user',
// 请求 API 的父路径
baseURL: 'https://some-domain.com/api/',
params: {
ID: 12345
},
// data 作为请求主体被发送的 JSON 数据 只适用于这些请求方法 'PUT', 'POST', 'PATCH'
data: {
firstName: 'Fred'
},
// timeout 指定请求超时的毫秒数(0 表示无超时时间)
timeout: 1000
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err);
})
3. 请求拦截器和响应拦截器
使用axios.create()方法创建一个实例
在实例上添加interceptors.request.use()请求拦截器
interceptors.response.use()响应拦截器
注意:我们在axios.create上添加的配置后,使用这个实例发出的所有请求中通用一处配置,所有请求都带有该配置。比如设置基准地址baseUrl、请求头headers等等。这也是我们封装axios的作用之一
1 | import axios from "axios"; |
4.post、get方法知识拓展
当项目中没有使用axios.create()方法封装axios实例时,在直接使用axios.get()和axiso.post()方法的情况下配置请求头等相关参数(这种情况极少,尽力避免这么做,不推荐)
4.1 axios.get(url,{})方法
在get方法中的第二个参数为一个对象,我们传递的参数及其配置都在这里面1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16axios.get(url,
{
//headers 配置请求头
headers: {
'Authorization': 'Bearer ' + token,
'token' : 'sessionId',
},
//传递的参数
params: {
param1: string,
param2: string
}
}
)
.then(res => fn)
.catch(e => fn)
4.2 axios.post(url,data,{})方法
axios.post()方法拥有三个参数url(请求地址); data(传递参数对象);{ }配置
只不过第三个参数也就是配置项一般很少使用1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18axios.post(
//参数1
url,
//参数2
{
'id':'1'
},
//参数3
{
headers: {
'Authorization': 'Bearer ' + token,
"Cookie" : 'sessionId',
'Content-Type': 'application/json'
}
}
)
.then(res => fn)
.catch(e => fn)