0%

Axios的封装、请求响应拦截器及其各种方法详解

1.安装axios

1
npm i axios

2. axios的请求方式

2.1 get请求

2.1.1 axios.get方法

1
2
3
4
5
6
7
8
9
10
11
12
//参数使用{ params:{} }方式,注意是{}内params:{}
axios.get("/student", {
params: {
name: "Lucy",
age: 10,
state: false,
}
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err);
})
1
2
3
4
5
6
7
// 简写方式,传递参数使用?
axios.get("/student?name=Lucy&age=10&state=false")
.then(res => {
console.log(res)
}).catch(err => {
console.error(err);
})

2.1.2 axios()方法

注意:method为请求方法,当为get时使用params传递参数

1
2
3
4
5
6
7
8
9
axios({
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
2
3
4
5
6
7
8
9
10
11
12
13
axios({
method: 'post', //请求方法包含(get,post,delete,put)等
url: '/student', //请求路径
data: { //当method为post时的传参方式,属性为data
name: "Lucy",
age: 10,
state: false
}
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err);
})

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
24
axios({
//配置请求头
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import axios from "axios";
import { ElMessage } from "element-plus"; // 使用element Message做消息提醒
// 创建一个 axios 实例
const service = axios.create({
baseURL: "http://。。。。。", //所有的请求地址前缀部分,`baseURL` 将自动加在每个请求 `url` 前面,除非 `url` 是一个绝对 URL。
timeout: 60000, // 请求超时时间毫秒
withCredentials: true, // 异步请求携带cookie
headers: {
// 设置后端需要的传参类型
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
},
});

// 添加请求拦截器,拦截处理后一定要return回去
service.interceptors.request.use(
function (config: any) {
// 在发送请求之前做些什么,比如我这里在请求头中携带token
config.headers.sessionToken = "asdfasdf234234234";
return config;
},
function (error) {
// 对请求错误做些什么
console.log(error);
return Promise.reject(error);
}
);

// 添加响应拦截器
service.interceptors.response.use(
function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
// data 是 axios 返回数据中的 data,也就是我们请求的结果数据
const data = response.data;
console.log(data, "响应拦截器的数据");

return data;
},
function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么,如401: 未登录 未登录则跳转登录页面等等
ElMessage.error("哎呀!请求出错了");
console.log(error);
return Promise.reject(error);
}
);

export default service;

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
16
axios.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
18
axios.post(
//参数1
url,
//参数2
{
'id':'1'
},
//参数3
{
headers: {
'Authorization': 'Bearer ' + token,
"Cookie" : 'sessionId',
'Content-Type': 'application/json'
}
}
)
.then(res => fn)
.catch(e => fn)

赏包辣条吃吧