service.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import axios, {
  2. AxiosError,
  3. type AxiosInstance,
  4. type AxiosResponse,
  5. type InternalAxiosRequestConfig,
  6. } from "axios";
  7. import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
  8. import { useUserStoreWithOut } from "@/stores/useUserStore";
  9. import qs from "qs";
  10. import { config } from "@/config/axios/config";
  11. import {
  12. getAccessToken,
  13. getRefreshToken,
  14. removeToken,
  15. setToken,
  16. } from "@utils/auth";
  17. import errorCode from "./errorCode";
  18. import { resetRouter } from "@/router";
  19. import { deleteUserCache } from "@hooks/useCache";
  20. const { result_code, base_url, request_timeout } = config;
  21. // 需要忽略的提示。忽略后,自动 Promise.reject('error')
  22. const ignoreMsgs = [
  23. "无效的刷新令牌", // 刷新令牌被删除时,不用提示
  24. "刷新令牌已过期", // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401,无法跳转到登出界面
  25. ];
  26. // 是否显示重新登录
  27. export const isRelogin = { show: false };
  28. export const reloginCancelKey = "reloginCancel";
  29. export const manualLogoutKey = "manualLogout";
  30. // Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
  31. // 请求队列
  32. let requestList: any[] = [];
  33. // 是否正在刷新中
  34. let isRefreshToken = false;
  35. // 请求白名单,无须token的接口
  36. const whiteList: string[] = ["/login", "/refresh-token"];
  37. // 创建axios实例
  38. const service: AxiosInstance = axios.create({
  39. baseURL: base_url, // api 的 base_url
  40. timeout: request_timeout, // 请求超时时间
  41. withCredentials: false, // 禁用 Cookie 等信息
  42. // 自定义参数序列化函数
  43. paramsSerializer: (params) => {
  44. return qs.stringify(params, { allowDots: true });
  45. },
  46. });
  47. // request拦截器
  48. service.interceptors.request.use(
  49. (config: InternalAxiosRequestConfig) => {
  50. config.headers["tenant-id"] = 1;
  51. // 是否需要设置 token
  52. let isToken = (config!.headers || {}).isToken === false;
  53. whiteList.some((v) => {
  54. if (config.url && config.url.indexOf(v) > -1) {
  55. return (isToken = false);
  56. }
  57. });
  58. if (getAccessToken() && !isToken) {
  59. config.headers.Authorization = "Bearer " + getAccessToken(); // 让每个请求携带自定义token
  60. }
  61. const method = config.method?.toUpperCase();
  62. // 防止 GET 请求缓存
  63. if (method === "GET") {
  64. config.headers["Cache-Control"] = "no-cache";
  65. config.headers["Pragma"] = "no-cache";
  66. }
  67. // 自定义参数序列化函数
  68. else if (method === "POST") {
  69. const contentType =
  70. config.headers["Content-Type"] || config.headers["content-type"];
  71. if (contentType === "application/x-www-form-urlencoded") {
  72. if (config.data && typeof config.data !== "string") {
  73. config.data = qs.stringify(config.data);
  74. }
  75. }
  76. }
  77. return config;
  78. },
  79. (error: AxiosError) => {
  80. // Do something with request error
  81. console.log(error); // for debug
  82. return Promise.reject(error);
  83. },
  84. );
  85. // response 拦截器
  86. service.interceptors.response.use(
  87. async (response: AxiosResponse<any>) => {
  88. let { data } = response;
  89. const config = response.config;
  90. if (!data) {
  91. // 返回“[HTTP]请求没有返回值”;
  92. throw new Error();
  93. }
  94. // 未设置状态码则默认成功状态
  95. // 二进制数据则直接返回,例如说 Excel 导出
  96. if (
  97. response.request.responseType === "blob" ||
  98. response.request.responseType === "arraybuffer"
  99. ) {
  100. // 注意:如果导出的响应为 json,说明可能失败了,不直接返回进行下载
  101. if (response.data.type !== "application/json") {
  102. return response.data;
  103. }
  104. data = await new Response(response.data).json();
  105. }
  106. const code = data.code || result_code;
  107. // 获取错误信息
  108. const msg = data.msg || (errorCode as any)[code] || errorCode.default;
  109. if (ignoreMsgs.indexOf(msg) !== -1) {
  110. // 如果是忽略的错误码,直接返回 msg 异常
  111. return Promise.reject(msg);
  112. } else if (code === 401) {
  113. // 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
  114. if (!isRefreshToken) {
  115. isRefreshToken = true;
  116. // 1. 如果获取不到刷新令牌,则只能执行登出操作
  117. if (!getRefreshToken()) {
  118. return handleAuthorized();
  119. }
  120. // 2. 进行刷新访问令牌
  121. try {
  122. const refreshTokenRes = await refreshToken();
  123. // 2.1 刷新成功,则回放队列的请求 + 当前请求
  124. setToken((await refreshTokenRes).data.data);
  125. config.headers!.Authorization = "Bearer " + getAccessToken();
  126. requestList.forEach((cb: any) => {
  127. cb();
  128. });
  129. requestList = [];
  130. return service(config);
  131. } catch (e) {
  132. // 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
  133. // 2.2 刷新失败,只回放队列的请求
  134. requestList.forEach((cb: any) => {
  135. cb();
  136. });
  137. // 提示是否要登出。即不回放当前请求!不然会形成递归
  138. return handleAuthorized();
  139. } finally {
  140. requestList = [];
  141. isRefreshToken = false;
  142. }
  143. } else {
  144. // 添加到队列,等待刷新获取到新的令牌
  145. return new Promise((resolve) => {
  146. requestList.push(() => {
  147. config.headers!.Authorization = "Bearer " + getAccessToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  148. resolve(service(config));
  149. });
  150. });
  151. }
  152. } else if (code === 500) {
  153. ElMessage.error(msg);
  154. return Promise.reject(new Error(msg));
  155. } else if (code === 901) {
  156. ElMessage.error({
  157. offset: 300,
  158. dangerouslyUseHTMLString: true,
  159. message: "演示模式,无法进行写操作!",
  160. });
  161. return Promise.reject(new Error(msg));
  162. } else if (code !== 200) {
  163. if (msg === "无效的刷新令牌") {
  164. // hard coding:忽略这个提示,直接登出
  165. console.log(msg);
  166. return handleAuthorized();
  167. } else {
  168. ElNotification.error({ title: msg });
  169. }
  170. return Promise.reject("error");
  171. } else {
  172. return data;
  173. }
  174. },
  175. (error: AxiosError) => {
  176. console.log("err" + error); // for debug
  177. let { message } = error;
  178. if (message === "Network Error") {
  179. message = "操作失败,系统异常!";
  180. } else if (message.includes("timeout")) {
  181. message = "接口请求超时,请刷新页面重试!";
  182. } else if (message.includes("Request failed with status code")) {
  183. message = "请求出错,请稍候重试" + message.substr(message.length - 3);
  184. }
  185. ElMessage.error(message);
  186. return Promise.reject(error);
  187. },
  188. );
  189. const refreshToken = async () => {
  190. axios.defaults.headers.common["tenant-id"] = 1;
  191. return await axios.post(
  192. base_url +
  193. "/admin-api/system/auth/refresh-token?refreshToken=" +
  194. getRefreshToken(),
  195. );
  196. };
  197. const handleAuthorized = () => {
  198. const isManualLogout = sessionStorage.getItem(manualLogoutKey) === "true";
  199. const isReloginCanceled = sessionStorage.getItem(reloginCancelKey) === "true";
  200. const ua = window.navigator.userAgent.toLowerCase();
  201. if (isManualLogout || isReloginCanceled) {
  202. deleteUserCache();
  203. removeToken();
  204. if (!window.location.href.includes("login")) {
  205. if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
  206. window.location.href = "/";
  207. } else {
  208. window.location.href = "/login";
  209. }
  210. }
  211. return Promise.reject("登录超时,请重新登录");
  212. }
  213. if (!isRelogin.show) {
  214. if (window.location.href.includes("login")) {
  215. return Promise.reject("登录超时,请重新登录");
  216. }
  217. isRelogin.show = true;
  218. ElMessageBox.confirm("登录超时,请重新登录", "确定", {
  219. showCancelButton: false,
  220. closeOnClickModal: false,
  221. showClose: false,
  222. closeOnPressEscape: false,
  223. confirmButtonText: "重新登录",
  224. cancelButtonText: "取消",
  225. type: "warning",
  226. })
  227. .then(async () => {
  228. sessionStorage.removeItem(reloginCancelKey);
  229. deleteUserCache(); // 删除用户缓存
  230. removeToken();
  231. isRelogin.show = false;
  232. window.location.href = "/login";
  233. })
  234. .catch(() => {
  235. sessionStorage.setItem(reloginCancelKey, "true");
  236. deleteUserCache(); // 删除用户缓存
  237. removeToken();
  238. isRelogin.show = false; // 重置显示状态
  239. if (ua.includes("dingtalk") || ua.includes("dingtalkwork")) {
  240. window.location.href = "/";
  241. } else {
  242. window.location.href = "/login";
  243. }
  244. });
  245. }
  246. return Promise.reject("登录超时,请重新登录");
  247. };
  248. export { service };