request.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
  2. import { useUserStore } from '@/store/modules/user';
  3. import { getToken } from '@/utils/auth';
  4. import { tansParams, blobValidate } from '@/utils/ruoyi';
  5. import cache from '@/plugins/cache';
  6. import { HttpStatus } from '@/enums/RespEnum';
  7. import { errorCode } from '@/utils/errorCode';
  8. import { LoadingInstance } from 'element-plus/es/components/loading/src/loading';
  9. import FileSaver from 'file-saver';
  10. import { getLanguage } from '@/lang';
  11. import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/utils/crypto';
  12. import { encrypt, decrypt } from '@/utils/jsencrypt';
  13. import router from '@/router';
  14. const encryptHeader = 'encrypt-key';
  15. let downloadLoadingInstance: LoadingInstance;
  16. // 是否显示重新登录
  17. export const isRelogin = { show: false };
  18. export const globalHeaders = () => {
  19. return {
  20. Authorization: 'Bearer ' + getToken(),
  21. clientid: import.meta.env.VITE_APP_CLIENT_ID
  22. };
  23. };
  24. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
  25. axios.defaults.headers['clientid'] = import.meta.env.VITE_APP_CLIENT_ID;
  26. // 创建 axios 实例
  27. const service = axios.create({
  28. // baseURL: import.meta.env.VITE_APP_BASE_API,
  29. // baseURL: 'http://192.168.1.126:8080',
  30. baseURL: 'http://meet2.sportsrobo.club:8080',
  31. // baseURL: 'http://localhost:8080',
  32. timeout: 300000 // 增加默认超时时间到5分钟
  33. });
  34. // 请求拦截器
  35. service.interceptors.request.use(
  36. (config: InternalAxiosRequestConfig) => {
  37. // 对应国际化资源文件后缀
  38. config.headers['Content-Language'] = getLanguage();
  39. const isToken = config.headers?.isToken === false;
  40. // 是否需要防止数据重复提交
  41. const isRepeatSubmit = config.headers?.repeatSubmit === false;
  42. // 是否需要加密
  43. const isEncrypt = config.headers?.isEncrypt === 'true';
  44. if (getToken() && !isToken) {
  45. config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  46. }
  47. // get请求映射params参数
  48. if (config.method === 'get' && config.params) {
  49. let url = config.url + '?' + tansParams(config.params);
  50. url = url.slice(0, -1);
  51. config.params = {};
  52. config.url = url;
  53. }
  54. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  55. const requestObj = {
  56. url: config.url,
  57. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  58. time: new Date().getTime()
  59. };
  60. const sessionObj = cache.session.getJSON('sessionObj');
  61. if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
  62. cache.session.setJSON('sessionObj', requestObj);
  63. } else {
  64. const s_url = sessionObj.url; // 请求地址
  65. const s_data = sessionObj.data; // 请求数据
  66. const s_time = sessionObj.time; // 请求时间
  67. const interval = 500; // 间隔时间(ms),小于此时间视为重复提交
  68. if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
  69. const message = '数据正在处理,请勿重复提交';
  70. console.warn(`[${s_url}]: ` + message);
  71. return Promise.reject(new Error(message));
  72. } else {
  73. cache.session.setJSON('sessionObj', requestObj);
  74. }
  75. }
  76. }
  77. if (import.meta.env.VITE_APP_ENCRYPT === 'true') {
  78. // 当开启参数加密
  79. if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
  80. // 生成一个 AES 密钥
  81. const aesKey = generateAesKey();
  82. config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
  83. config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) : encryptWithAes(config.data, aesKey);
  84. }
  85. }
  86. // FormData数据去请求头Content-Type
  87. if (config.data instanceof FormData) {
  88. delete config.headers['Content-Type'];
  89. }
  90. return config;
  91. },
  92. (error: any) => {
  93. return Promise.reject(error);
  94. }
  95. );
  96. // 响应拦截器
  97. service.interceptors.response.use(
  98. (res: AxiosResponse) => {
  99. if (import.meta.env.VITE_APP_ENCRYPT === 'true') {
  100. // 加密后的 AES 秘钥
  101. const keyStr = res.headers[encryptHeader];
  102. // 加密
  103. if (keyStr != null && keyStr != '') {
  104. const data = res.data;
  105. // 请求体 AES 解密
  106. const base64Str = decrypt(keyStr);
  107. // base64 解码 得到请求头的 AES 秘钥
  108. const aesKey = decryptBase64(base64Str.toString());
  109. // aesKey 解码 data
  110. const decryptData = decryptWithAes(data, aesKey);
  111. // 将结果 (得到的是 JSON 字符串) 转为 JSON
  112. res.data = JSON.parse(decryptData);
  113. }
  114. }
  115. // 未设置状态码则默认成功状态
  116. const code = res.data.code || HttpStatus.SUCCESS;
  117. // 获取错误信息
  118. const msg = errorCode[code] || res.data.msg || errorCode['default'];
  119. // 二进制数据则直接返回
  120. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer' || res.config.responseType === 'blob' || res.config.responseType === 'arraybuffer') {
  121. return res.data;
  122. }
  123. if (code === 401) {
  124. // prettier-ignore
  125. if (!isRelogin.show) {
  126. isRelogin.show = true;
  127. ElMessageBox.confirm("登录状态已过期,您可以继续留在该页面,或者重新登录", "系统提示", {
  128. confirmButtonText: "重新登录",
  129. cancelButtonText: "取消",
  130. type: "warning"
  131. }).then(() => {
  132. isRelogin.show = false;
  133. useUserStore().logout().then(() => {
  134. router.replace({
  135. path: "/login",
  136. query: {
  137. redirect: encodeURIComponent(router.currentRoute.value.fullPath || "/")
  138. }
  139. });
  140. });
  141. }).catch(() => {
  142. isRelogin.show = false;
  143. });
  144. }
  145. return Promise.reject('无效的会话,或者会话已过期,请重新登录。');
  146. } else if (code === HttpStatus.SERVER_ERROR) {
  147. ElMessage({ message: msg, type: 'error' });
  148. return Promise.reject(new Error(msg));
  149. } else if (code === HttpStatus.WARN) {
  150. ElMessage({ message: msg, type: 'warning' });
  151. return Promise.reject(new Error(msg));
  152. } else if (code !== HttpStatus.SUCCESS) {
  153. ElNotification.error({ title: msg });
  154. return Promise.reject('error');
  155. } else {
  156. return Promise.resolve(res.data);
  157. }
  158. },
  159. (error: any) => {
  160. let { message } = error;
  161. if (message == 'Network Error') {
  162. message = '后端接口连接异常';
  163. } else if (message.includes('timeout')) {
  164. message = '系统接口请求超时';
  165. } else if (message.includes('Request failed with status code')) {
  166. message = '系统接口' + message.substr(message.length - 3) + '异常';
  167. }
  168. ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
  169. return Promise.reject(error);
  170. }
  171. );
  172. // 通用下载方法
  173. export function download(url: string, params: any, fileName: string) {
  174. downloadLoadingInstance = ElLoading.service({ text: '正在下载数据,请稍候', background: 'rgba(0, 0, 0, 0.7)' });
  175. // prettier-ignore
  176. return service.post(url, params, {
  177. transformRequest: [
  178. (params: any) => {
  179. return tansParams(params);
  180. }
  181. ],
  182. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  183. responseType: "blob"
  184. }).then(async (resp: any) => {
  185. const isLogin = blobValidate(resp);
  186. if (isLogin) {
  187. const blob = new Blob([resp]);
  188. FileSaver.saveAs(blob, fileName);
  189. } else {
  190. const blob = new Blob([resp]);
  191. const resText = await blob.text();
  192. const rspObj = JSON.parse(resText);
  193. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
  194. ElMessage.error(errMsg);
  195. }
  196. downloadLoadingInstance.close();
  197. }).catch((r: any) => {
  198. console.error(r);
  199. ElMessage.error("下载文件出现错误,请联系管理员!");
  200. downloadLoadingInstance.close();
  201. });
  202. }
  203. // 导出 axios 实例
  204. export default service;