推荐封装方案
1. 创建Axios实例
import axios, {
AxiosRequestConfig, AxiosResponse } from 'axios';
const service = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json' }
});
2. 请求拦截器(Token、Loading)
let loadingCount = 0;
service.interceptors.request.use((config: AxiosRequestConfig) => {
const token = store.state.token;
if (token) config.headers!.Authorization = `Bearer ${
token}`;
if (config.showLoading) {
loadingCount++;
showLoading();
}
return config;
});
3. 响应拦截器(错误处理、Token过期)
service.interceptors.response.use(
(response: AxiosResponse) => {
if (response.config.showLoading) {
loadingCount--;
if (loadingCount === 0) hideLoading();
}
const {
code, message, data } = response.data;
if (code !== 200)