request.js 7.1 KB

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