Axios拦截器可以用于在发送请求或响应返回之前拦截和处理数据,对于需要在拦截器中添加一个过期时间的场景,可以通过设置一个定时器来实现。
以下是一个示例代码:
import axios from 'axios';
// 定义请求拦截器
let interceptor = axios.interceptors.request.use(config => {
// 在请求发送之前设置定时器
config.timeout = 5000;
return config;
}, error => Promise.reject(error));
// 发送请求
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
})
.finally(() => {
// 取消请求拦截器
axios.interceptors.request.eject(interceptor);
});
在上面的代码中,我们定义了一个请求拦截器,并在拦截器中设置了一个超时时间为5秒的定时器。在发送请求之后,我们还可以通过调用axios.interceptors.request.eject(interceptor)方法来取消请求拦截器。
下一篇:Axios拦截器和异步加载