request.ts 8.7 KB

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