123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import axios, {
- type AxiosInstance,
- type InternalAxiosRequestConfig,
- type AxiosResponse,
- } from "axios";
- export enum ResponseStatusCode {
- SUCCESS = 0,
- TOKEN_INVALID = 5001,
- TOKEN_INVALID2 = 5002,
- }
- interface DageConfig<D = any> extends InternalAxiosRequestConfig<D> {
- /**
- * 隐藏错误提醒
- */
- hidden?: boolean;
- }
- export interface DageResponse<T = any, D = any> extends AxiosResponse<T, D> {
- code: number;
- msg: string;
- }
- interface Service extends AxiosInstance {
- get<T = any, R = DageResponse<T>, D = any>(
- url: string,
- config?: Partial<DageConfig<D>>
- ): Promise<R>;
- post<T = any, R = DageResponse<T>, D = any>(
- url: string,
- data?: D,
- config?: DageConfig<D>
- ): Promise<R>;
- }
- const service: Service = axios.create({
- baseURL: process.env.REACT_APP_BACKEND_URL,
- timeout: 5 * 60 * 1000,
- headers: {
- "Cache-Control": "no-cache",
- "Content-Type": "application/json;charset=UTF-8",
- "X-Requested-With": "XMLHttpRequest",
- },
- });
- /**
- * 服务端接口empty字符串跟null返回的结果不同,过滤掉empty字符串
- * @param params
- * @param emptyString 是否过滤空字符串
- */
- function filterEmptyKey(params: any, emptyString = false) {
- if (Array.isArray(params) || params == null) {
- return params;
- }
- Object.keys(params).forEach((key) => {
- if (params[key] === null || (emptyString && params[key] === "")) {
- delete params[key];
- }
- });
- }
- service.interceptors.request.use((config: DageConfig) => {
- if (config.method === "post") {
- if (!(config.data instanceof FormData)) {
- const params = {
- ...config.data,
- };
- filterEmptyKey(params); // 过滤空字符串
- config.data = params;
- }
- } else if (config.method === "get") {
- config.params = {
- _t: new Date().getTime() / 1000,
- ...config.params,
- };
- filterEmptyKey(config.params, true);
- }
- return config;
- });
- service.interceptors.response.use(
- (res) => {
- const { data }: { config: DageConfig; data: DageResponse } = res;
- return data || {};
- },
- (error) => {
- return new Promise((res, rej) => {
- rej(error);
- });
- }
- );
- export default service as Required<Service>;
|