Newer
Older
DH_Apicture / src / utils / request.js
@zhangqy zhangqy 29 days ago 5 KB 还原
  1. import axios from 'axios';
  2. import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus';
  3. import { getToken } from '@/utils/auth';
  4. import errorCode from '@/utils/errorCode';
  5. import { tansParams, blobValidate } from '@/utils/ruoyi';
  6. import cache from '@/plugins/cache';
  7. import { saveAs } from 'file-saver';
  8. import useUserStore from '@/store/modules/user';
  9. let downloadLoadingInstance;
  10. // 是否显示重新登录
  11. export let isRelogin = { show: false };
  12.  
  13. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
  14. // 创建axios实例
  15. const service = axios.create({
  16. // axios中请求配置有baseURL选项,表示请求URL公共部分
  17. baseURL: import.meta.env.VITE_APP_BASE_API,
  18. // 超时
  19. timeout: 30000,
  20. });
  21.  
  22. // request拦截器
  23. service.interceptors.request.use(
  24. config => {
  25. // console.log("config.url", config.url);
  26. // 是否需要设置 token
  27. const isToken = (config.headers || {}).isToken === false;
  28. // 是否需要防止数据重复提交
  29. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
  30. if (getToken() && !isToken) {
  31. config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
  32. }
  33.  
  34.  
  35. if (config.method === 'get' && config.params) {
  36. // get请求映射params参数
  37. let url = config.url + '?' + tansParams(config.params);
  38. url = url.slice(0, -1);
  39. config.params = {};
  40. config.url = url;
  41. }
  42. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  43. const requestObj = {
  44. url: config.url,
  45. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  46. time: new Date().getTime(),
  47. };
  48. const sessionObj = cache.session.getJSON('sessionObj');
  49. if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
  50. cache.session.setJSON('sessionObj', requestObj);
  51. } else {
  52. const s_url = sessionObj.url; // 请求地址
  53. const s_data = sessionObj.data; // 请求数据
  54. const s_time = sessionObj.time; // 请求时间
  55. const interval = 1000; // 间隔时间(ms),小于此时间视为重复提交
  56. if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
  57. const message = '数据正在处理,请勿重复提交';
  58. console.warn(`[${s_url}]: ` + message);
  59. return Promise.reject(new Error(message));
  60. } else {
  61. cache.session.setJSON('sessionObj', requestObj);
  62. }
  63. }
  64. }
  65. return config;
  66. },
  67. error => {
  68. console.log(error);
  69. Promise.reject(error);
  70. }
  71. );
  72.  
  73. // 响应拦截器
  74. service.interceptors.response.use(
  75. res => {
  76. // 未设置状态码则默认成功状态
  77. const code = res.data.code || 200;
  78. // 获取错误信息
  79. const msg = errorCode[code] || res.data.msg || errorCode['default'];
  80. // 二进制数据则直接返回
  81. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
  82. return res.data;
  83. }
  84. if (code === 401) {
  85. if (!isRelogin.show) {
  86. isRelogin.show = true;
  87. ElMessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  88. confirmButtonText: '重新登录',
  89. cancelButtonText: '取消',
  90. type: 'warning',
  91. })
  92. .then(() => {
  93. isRelogin.show = false;
  94. useUserStore()
  95. .logOut()
  96. .then(() => {
  97. location.href = '/index';
  98. });
  99. })
  100. .catch(() => {
  101. isRelogin.show = false;
  102. });
  103. }
  104. return Promise.reject('无效的会话,或者会话已过期,请重新登录。');
  105. } else if (code === 500) {
  106. ElMessage({ message: msg, type: 'error' });
  107. return Promise.reject(new Error(msg));
  108. } else if (code === 601) {
  109. ElMessage({ message: msg, type: 'warning' });
  110. return Promise.reject(new Error(msg));
  111. } else if (code !== 200) {
  112. ElNotification.error({ title: msg });
  113. return Promise.reject('error');
  114. } else {
  115. return Promise.resolve(res.data);
  116. }
  117. },
  118. error => {
  119. console.log('err' + error);
  120. let { message } = error;
  121. if (message == 'Network Error') {
  122. message = '后端接口连接异常';
  123. } else if (message.includes('timeout')) {
  124. message = '系统接口请求超时';
  125. } else if (message.includes('Request failed with status code')) {
  126. message = '系统接口' + message.substr(message.length - 3) + '异常';
  127. }
  128. ElMessage({ message: message, type: 'error', duration: 5 * 1000 });
  129. return Promise.reject(error);
  130. }
  131. );
  132.  
  133. // 通用下载方法
  134. export function download(url, params, filename, config) {
  135. downloadLoadingInstance = ElLoading.service({
  136. text: '正在下载数据,请稍候',
  137. background: 'rgba(0, 0, 0, 0.7)',
  138. });
  139. return service
  140. .post(url, params, {
  141. transformRequest: [
  142. params => {
  143. return tansParams(params);
  144. },
  145. ],
  146. headers: {
  147. 'Content-Type': 'application/x-www-form-urlencoded',
  148. },
  149. // headers: {
  150. // "Content-Type": "application/json;charset=UTF-8",
  151. // },
  152. responseType: 'blob',
  153. ...config,
  154. })
  155. .then(async data => {
  156. const isLogin = await blobValidate(data);
  157. if (isLogin) {
  158. const blob = new Blob([data]);
  159. saveAs(blob, filename);
  160. } else {
  161. const resText = await data.text();
  162. const rspObj = JSON.parse(resText);
  163. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
  164. ElMessage.error(errMsg);
  165. }
  166. downloadLoadingInstance.close();
  167. })
  168. .catch(r => {
  169. console.error(r);
  170. ElMessage.error('下载文件出现错误,请联系管理员!');
  171. downloadLoadingInstance.close();
  172. });
  173. }
  174.  
  175. export default service;