index.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import axios, { AxiosResponse } from "axios";
  2. import qs from "qs";
  3. import { openLoading, closeLoading } from "./loading";
  4. import { openErrorMsg } from "./errorMsg";
  5. import {
  6. fromUrls,
  7. fileUrls,
  8. GetUrls,
  9. PostUrls,
  10. notLoginUrls,
  11. baseURL,
  12. unAuthCode,
  13. successCode,
  14. } from "./config";
  15. import { router } from "@/router";
  16. import { RouteName } from "@/router/config";
  17. export * from "./urls";
  18. export * from "./config";
  19. export * from "./loading";
  20. export * from "./errorMsg";
  21. export type AuthHook = () => {
  22. token: string;
  23. userId: string;
  24. clear: () => void;
  25. };
  26. export const setAuthHook = (hook: AuthHook) => (getAuth = hook);
  27. let getAuth: AuthHook = () => ({ token: "", userId: "0", clear: () => {} });
  28. axios.defaults.baseURL = baseURL;
  29. axios.interceptors.request.use(async (config) => {
  30. if (config.method === "get" && config.params) {
  31. for (const key in config.params) {
  32. const val = config.params[key];
  33. if (typeof val === "string") {
  34. config.params[key] = val.replaceAll(/[\[\]]/g, "").trim();
  35. }
  36. }
  37. }
  38. if (!config.url) {
  39. return config;
  40. }
  41. const { token, userId } = getAuth();
  42. config.headers.token = token;
  43. config.headers.userid = userId;
  44. const hasIgnore = config.params ? "ingoreRes" in config.params : false;
  45. if (!hasIgnore) {
  46. if (!token && !~notLoginUrls.indexOf(config.url)) {
  47. router.replace({ name: RouteName.login });
  48. throw "用户未登录";
  49. }
  50. }
  51. if (~GetUrls.indexOf(config.url)) {
  52. config.method = "GET";
  53. } else if (~PostUrls.indexOf(config.url)) {
  54. config.method = "POST";
  55. if (!config.data && config.params) {
  56. config.data = config.params;
  57. }
  58. }
  59. // 处理需要用表单上传的请求
  60. if (~fromUrls.indexOf(config.url)) {
  61. config.data = qs.stringify(config.data);
  62. config.headers["Content-Type"] =
  63. "application/x-www-form-urlencoded; charset=utf-8;";
  64. } else if (~fileUrls.indexOf(config.url)) {
  65. const fromData = new FormData();
  66. Object.keys(config.data).forEach((key) => {
  67. fromData.append(key, config.data[key]);
  68. });
  69. config.data = fromData;
  70. config.headers["Content-Type"] = "multipart/form-data";
  71. }
  72. openLoading(config.url);
  73. return config;
  74. });
  75. const responseInterceptor = (res: AxiosResponse<any, any>) => {
  76. closeLoading();
  77. const hasIgnore = res.config.params
  78. ? "ingoreRes" in res.config.params
  79. : false;
  80. if (!successCode.includes(res.data.code) && !hasIgnore) {
  81. let errMsg = res.data.msg || res.data.message;
  82. openErrorMsg(errMsg);
  83. if (
  84. ~unAuthCode.indexOf(res.data.code) ||
  85. errMsg === "token已经失效,请重新登录"
  86. ) {
  87. router.replace({ name: RouteName.login });
  88. getAuth().clear();
  89. }
  90. throw res.data.msg;
  91. }
  92. return res.data;
  93. };
  94. axios.interceptors.response.use(responseInterceptor, (error) => {
  95. closeLoading();
  96. if (error.response && error.response.data) {
  97. return responseInterceptor(error.response);
  98. } else {
  99. openErrorMsg(
  100. typeof error === "string" ? error : "请求失败,服务端发生了点小故障!"
  101. );
  102. return Promise.reject(error);
  103. }
  104. });
  105. export { axios };
  106. export type PaggingReq<T> = T & {
  107. pageNum: number;
  108. pageSize: number;
  109. };
  110. export type PaggingRes<T> = T & {
  111. total: number;
  112. list: T[];
  113. };