interceptor.ts 1.7 KB
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
  status: 'success' | 'fail' | 'error';
  msg: string;
  code: number;
  data: T;
}

export interface ServiceResponse<T = unknown> extends HttpResponse<T> {
  meta: { current: number; limit: number; total: number };
}

if (import.meta.env.VITE_API_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_URL;
}

axios.interceptors.request.use(
  // @ts-ignore
  (config: AxiosRequestConfig) => {
    if (!config.url?.startsWith('/provider')) {
      config.baseURL = `${config.baseURL}/user`;
    }

    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  // @ts-ignore
  async (response: AxiosResponse<ServiceResponse>): Promise<ServiceResponse | unknown> => {
    if (response.data instanceof Blob) {
      return Promise.resolve(response);
    }

    return Promise.resolve(response.data);
  },
  (error) => {
    if (error.response.status === 401) {
      // clearToken();
      window.location.reload();
      Message.warning({ id: 'token_lose', content: '登陆信息已失效,请重新登陆...' });
    } else {
      Message.error({
        id: 'service_error',
        content: error.response.data.msg || error.msg || 'Request Error',
        duration: 5 * 1000,
      });
    }

    return Promise.reject(error);
  }
);