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