request.ts 8.1 KB

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