HTTP请求拦截各个阶段Vue.js
郭旭升 Lv6

axios 拦截器

使用axios的拦截器来获取HTTP请求的各个阶段。拦截器是一种机制,可以在HTTP请求或响应被发送或接收之前拦截它们,并对它们进行处理。在axios中,您可以使用request拦截器来获取HTTP请求的各个阶段,例如开始发送请求、已发送请求、正在等待响应、已接收响应等。

下面是一个使用axios拦截器获取HTTP请求阶段的示例:

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
import axios from 'axios';

axios.interceptors.request.use(config => {
console.log('Starting request', config);
return config;
});

axios.interceptors.response.use(response => {
console.log('Received response', response);
return response;
}, error => {
console.log('Received error', error);
return Promise.reject(error);
});

export default {
methods: {
async postData() {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1,
});
console.log('Received data', response.data);
} catch (error) {
console.log('Caught error', error);
}
},
},
};

在这个示例中,我们使用axios.interceptors.request.use()方法来定义一个request拦截器,它会在HTTP请求开始发送时被调用,并打印出请求的配置信息。我们还使用axios.interceptors.response.use()方法来定义一个response拦截器,它会在HTTP响应被接收时被调用,并打印出响应的数据。如果有错误,它将被记录在控制台中。

 Comments