请用typescript封装axios的拦截器
时间: 2023-10-08 13:14:49 浏览: 90
好的,以下是使用TypeScript封装Axios拦截器的示例代码:
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
class AxiosInterceptor {
private axiosInstance: AxiosInstance;
constructor(baseURL: string, timeout = 10000) {
this.axiosInstance = axios.create({
baseURL,
timeout,
});
this.requestInterceptor();
this.responseInterceptor();
}
private requestInterceptor(): void {
this.axiosInstance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 在发送请求之前做些什么
// 比如添加token到header中
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
}
private responseInterceptor(): void {
this.axiosInstance.interceptors.response.use(
(response: AxiosResponse) => {
// 对响应数据做点什么
return response;
},
(error) => {
// 对响应错误做点什么
if (error.response.status === 401) {
// token失效,跳转到登录页
window.location.href = '/login';
}
return Promise.reject(error);
}
);
}
public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
return this.axiosInstance.get<T>(url, config);
}
public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
return this.axiosInstance.post<T>(url, data, config);
}
public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
return this.axiosInstance.put<T>(url, data, config);
}
public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
return this.axiosInstance.delete<T>(url, config);
}
}
export default AxiosInterceptor;
```
这个类使用了Axios的拦截器功能,在请求发送前和响应返回后进行一些操作,比如添加token到请求header中,或者在token失效后跳转到登录页。类中还封装了常用的get、post、put、delete等HTTP请求方法,可以直接调用。
阅读全文