Skip to content

Instantly share code, notes, and snippets.

@ilaipi
Last active January 11, 2024 01:13
Show Gist options
  • Save ilaipi/a84421601d1559ee71597b846d2d9306 to your computer and use it in GitHub Desktop.
Save ilaipi/a84421601d1559ee71597b846d2d9306 to your computer and use it in GitHub Desktop.
axios interceptor
import axios from 'axios';
import type { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';
export interface HttpResponse<T = unknown> {
status: string;
message: string;
code: number;
data: T;
}
const baseURL = import.meta.env.VITE_API_BASE_URL;
if (baseURL) {
axios.defaults.baseURL = baseURL;
}
let isRefreshing = false;
let requests: any[] = [];
async function refreshToken() {
// instance是当前request.js中已创建的axios实例
return axios.post('/refreshtoken').then((res: AxiosResponse) => res.data);
}
axios.interceptors.request.use(
(config: AxiosRequestConfig) => {
// let each request carry token
// this example using the JWT token
// Authorization is a custom headers key
// please modify it according to the actual situation
const token = getToken();
if (token) {
if (!config.headers) {
config.headers = {};
}
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error: AxiosError) => {
// do something
return Promise.reject(error);
}
);
// add response interceptors
axios.interceptors.response.use(
(response: AxiosResponse<HttpResponse>) => {
const { code } = response.data;
if (
[50008, 50012, 50014].includes(code) &&
response.config.url !== '/api/user-info'
) {
const { config } = response;
if (!isRefreshing) {
isRefreshing = true;
return refreshToken()
.then((res2: AxiosResponse) => {
const { token } = res2;
config.headers = config.headers || {};
config.headers['Authorization'] = `Bearer ${token}`;
config.baseURL = '';
// 已经刷新了token,将所有队列中的请求进行重试
requests.forEach((cb) => cb(token));
requests = [];
// 再将当前请求重试
return axios(config);
})
.catch((res) => {
console.error('refreshtoken error =>', res);
window.location.href = '/';
})
.finally(() => {
isRefreshing = false;
});
}
return new Promise((resolve) => {
requests.push((token: string) => {
config.baseURL = '';
config.headers = config.headers || {};
config.headers['Authorization'] = `Bearer ${token}`;
resolve(axios(config));
});
});
}
return response;
},
(error: AxiosError) => {
Message.error({
content: error.message || 'Request Error',
duration: 5 * 1000,
});
return Promise.reject(error);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment