http.ts 5.5 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. const TIMEOUT = 10000
  10. const REPEAT_SUBMIT_DEFAULT_INTERVAL = 1000
  11. const CACHE_SIZE_LIMIT = 5 * 1024 * 1024
  12. const ERROR_MESSAGE_DURATION = 5000
  13. let downloadLoadingInstance: any
  14. export let isRelogin = { show: false }
  15. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  16. const service = axios.create({
  17. baseURL: import.meta.env.VITE_APP_BASE_API,
  18. timeout: TIMEOUT
  19. })
  20. service.interceptors.request.use(
  21. config => {
  22. const isToken = (config.headers || {}).isToken === false
  23. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  24. const interval = (config.headers || {}).interval || REPEAT_SUBMIT_DEFAULT_INTERVAL
  25. if (getToken() && !isToken) {
  26. config.headers['Authorization'] = 'Bearer ' + getToken()
  27. }
  28. if (config.method === 'get' && config.params) {
  29. let url = config.url + '?' + tansParams(config.params)
  30. url = url.slice(0, -1)
  31. config.params = {}
  32. config.url = url
  33. }
  34. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  35. const requestObj = {
  36. url: config.url,
  37. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  38. time: new Date().getTime()
  39. }
  40. const requestSize = JSON.stringify(requestObj).length
  41. if (requestSize >= CACHE_SIZE_LIMIT) {
  42. console.warn(`[${config.url}]: 请求数据大小超出允许的5M限制,无法进行防重复提交验证。`)
  43. return config
  44. }
  45. const sessionObj = cache.session.getJSON('sessionObj')
  46. if (!sessionObj) {
  47. cache.session.setJSON('sessionObj', requestObj)
  48. } else {
  49. const { url: s_url, data: s_data, time: s_time } = sessionObj
  50. if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
  51. const message = '数据正在处理,请勿重复提交'
  52. console.warn(`[${s_url}]: ${message}`)
  53. return Promise.reject(new Error(message))
  54. }
  55. cache.session.setJSON('sessionObj', requestObj)
  56. }
  57. }
  58. return config
  59. },
  60. error => {
  61. console.log(error)
  62. return Promise.reject(error)
  63. }
  64. )
  65. service.interceptors.response.use(
  66. res => {
  67. const code = res.data.code || 200
  68. const msg = errorCode[code] || res.data.msg || errorCode['default']
  69. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
  70. return res.data
  71. }
  72. const codeHandlers = {
  73. 401: () => {
  74. if (!isRelogin.show) {
  75. isRelogin.show = true
  76. ElMessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  77. confirmButtonText: '重新登录',
  78. cancelButtonText: '取消',
  79. type: 'warning'
  80. })
  81. .then(() => {
  82. isRelogin.show = false
  83. useUserStore()
  84. .logOut()
  85. .then(() => {
  86. location.href = '/index'
  87. })
  88. })
  89. .catch(() => {
  90. isRelogin.show = false
  91. })
  92. }
  93. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  94. },
  95. 500: () => {
  96. ElMessage({ message: msg, type: 'error' })
  97. return Promise.reject(new Error(msg))
  98. },
  99. 601: () => {
  100. ElMessage({ message: msg, type: 'warning' })
  101. return Promise.reject(new Error(msg))
  102. }
  103. }
  104. if (codeHandlers[code]) {
  105. return codeHandlers[code]()
  106. }
  107. if (code !== 200) {
  108. ElNotification.error({ title: msg })
  109. return Promise.reject('error')
  110. }
  111. return Promise.resolve(res.data)
  112. },
  113. error => {
  114. console.log('err' + error)
  115. let { message } = error
  116. const errorMessages = {
  117. 'Network Error': '后端接口连接异常',
  118. timeout: '系统接口请求超时',
  119. 'Request failed with status code': `系统接口${message.slice(-3)}异常`
  120. }
  121. for (const [key, value] of Object.entries(errorMessages)) {
  122. if (message.includes(key)) {
  123. message = value
  124. break
  125. }
  126. }
  127. ElMessage({ message, type: 'error', duration: ERROR_MESSAGE_DURATION })
  128. return Promise.reject(error)
  129. }
  130. )
  131. export function download(url, params, filename, config) {
  132. downloadLoadingInstance = ElLoading.service({
  133. text: '正在下载数据,请稍候',
  134. background: 'rgba(0, 0, 0, 0.7)'
  135. })
  136. return service
  137. .post(url, params, {
  138. transformRequest: [params => tansParams(params)],
  139. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  140. responseType: 'blob',
  141. ...config
  142. })
  143. .then(async data => {
  144. const isBlob = blobValidate(data)
  145. if (isBlob) {
  146. const blob = new Blob([data])
  147. saveAs(blob, filename)
  148. } else {
  149. const resText = await data.text()
  150. const rspObj = JSON.parse(resText)
  151. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  152. ElMessage.error(errMsg)
  153. }
  154. downloadLoadingInstance.close()
  155. })
  156. .catch(r => {
  157. console.error(r)
  158. ElMessage.error('下载文件出现错误,请联系管理员!')
  159. downloadLoadingInstance.close()
  160. })
  161. }
  162. export default service