services.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import axios, {
  2. type AxiosInstance,
  3. type InternalAxiosRequestConfig,
  4. type AxiosResponse,
  5. } from "axios";
  6. export enum ResponseStatusCode {
  7. SUCCESS = 0,
  8. TOKEN_INVALID = 5001,
  9. TOKEN_INVALID2 = 5002,
  10. }
  11. interface DageConfig<D = any> extends InternalAxiosRequestConfig<D> {
  12. /**
  13. * 隐藏错误提醒
  14. */
  15. hidden?: boolean;
  16. }
  17. export interface DageResponse<T = any, D = any> extends AxiosResponse<T, D> {
  18. code: number;
  19. msg: string;
  20. }
  21. interface Service extends AxiosInstance {
  22. get<T = any, R = DageResponse<T>, D = any>(
  23. url: string,
  24. config?: Partial<DageConfig<D>>
  25. ): Promise<R>;
  26. post<T = any, R = DageResponse<T>, D = any>(
  27. url: string,
  28. data?: D,
  29. config?: DageConfig<D>
  30. ): Promise<R>;
  31. }
  32. const service: Service = axios.create({
  33. baseURL: process.env.REACT_APP_BACKEND_URL,
  34. timeout: 5 * 60 * 1000,
  35. headers: {
  36. "Cache-Control": "no-cache",
  37. "Content-Type": "application/json;charset=UTF-8",
  38. "X-Requested-With": "XMLHttpRequest",
  39. },
  40. });
  41. /**
  42. * 服务端接口empty字符串跟null返回的结果不同,过滤掉empty字符串
  43. * @param params
  44. * @param emptyString 是否过滤空字符串
  45. */
  46. function filterEmptyKey(params: any, emptyString = false) {
  47. if (Array.isArray(params) || params == null) {
  48. return params;
  49. }
  50. Object.keys(params).forEach((key) => {
  51. if (params[key] === null || (emptyString && params[key] === "")) {
  52. delete params[key];
  53. }
  54. });
  55. }
  56. service.interceptors.request.use((config: DageConfig) => {
  57. if (config.method === "post") {
  58. if (!(config.data instanceof FormData)) {
  59. const params = {
  60. ...config.data,
  61. };
  62. filterEmptyKey(params); // 过滤空字符串
  63. config.data = params;
  64. }
  65. } else if (config.method === "get") {
  66. config.params = {
  67. _t: new Date().getTime() / 1000,
  68. ...config.params,
  69. };
  70. filterEmptyKey(config.params, true);
  71. }
  72. return config;
  73. });
  74. service.interceptors.response.use(
  75. (res) => {
  76. const { data }: { config: DageConfig; data: DageResponse } = res;
  77. return data || {};
  78. },
  79. (error) => {
  80. return new Promise((res, rej) => {
  81. rej(error);
  82. });
  83. }
  84. );
  85. export default service as Required<Service>;