axiosReq.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import axios from 'axios'
  2. import router from '@/router'
  3. import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
  4. import { getToken, setToken, removeToken } from '@/utils/auth'
  5. import { AxiosConfigTy, AxiosReqTy, ObjTy } from '~/common'
  6. import { useUserStore } from '@/store/user'
  7. let reqConfig: any
  8. let loadingE: any
  9. const service: any = axios.create()
  10. // 请求拦截
  11. service.interceptors.request.use(
  12. (request: AxiosReqTy) => {
  13. const route = router.currentRoute
  14. const data = request.data!
  15. const authMap = useUserStore().authMap
  16. if (!data.id || data.id !== DATACONTENT_ID.loginId) {
  17. const role = route.value.meta?.roles?.[0]
  18. if (role && authMap[role]) {
  19. request.headers['auth-id'] = authMap[role]
  20. }
  21. }
  22. // token setting
  23. request.headers['token'] = getToken()
  24. /* download file*/
  25. if (request.isDownLoadFile) {
  26. request.responseType = 'blob'
  27. }
  28. /* upload file*/
  29. if (request.isUploadFile) {
  30. request.headers['Content-Type'] = 'application/json'
  31. }
  32. reqConfig = request
  33. if (request.bfLoading) {
  34. loadingE = ElLoading.service({
  35. lock: true,
  36. text: '数据载入中',
  37. // spinner: 'el-icon-ElLoading',
  38. background: 'rgba(0, 0, 0, 0.1)',
  39. })
  40. }
  41. /*
  42. *params会拼接到url上
  43. * */
  44. if (request.isParams) {
  45. request.params = request.data
  46. request.data = {}
  47. }
  48. return request
  49. },
  50. (err: any) => {
  51. Promise.reject(err)
  52. }
  53. )
  54. // 响应拦截
  55. service.interceptors.response.use(
  56. (response) => {
  57. const res = response.data
  58. // if the custom code is not 20000, it is judged as an error.
  59. if (res.code != '0') {
  60. ElMessage({
  61. message: '执行失败',
  62. type: 'error',
  63. duration: 5 * 1000,
  64. })
  65. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  66. if (res.code === 500 || res.code === 50012 || res.code === 50014) {
  67. // to re-login
  68. ElMessageBox.confirm(
  69. 'You have been logged out, you can cancel to stay on this page, or log in again',
  70. 'Confirm logout',
  71. {
  72. confirmButtonText: 'Re-Login',
  73. cancelButtonText: 'Cancel',
  74. type: 'warning',
  75. }
  76. ).then(async () => {
  77. sessionStorage.removeItem('userName')
  78. // store.dispatch("app/toggleOutflag", false);
  79. await useUserStore().logout()
  80. router.push(`/login`)
  81. })
  82. }
  83. return Promise.reject(res.message || res.returnData?.message || 'Error')
  84. } else {
  85. return res
  86. }
  87. },
  88. (error) => {
  89. const des500 = `${error}`.split(' ').includes('500')
  90. if (des500) {
  91. ElMessage({
  92. message: '身份令牌过期或失效,即将重新登录',
  93. type: 'error',
  94. duration: 3 * 1000,
  95. onClose: async () => {
  96. sessionStorage.clear()
  97. removeToken() // must remove token first
  98. removeToken('codeToken')
  99. removeToken('systemSet')
  100. removeToken('userid')
  101. // store.dispatch('app/toggleOutflag', false)
  102. // await store.dispatch('user/resetToken')
  103. useUserStore().resetState()
  104. router.push(`/login`)
  105. location.reload()
  106. },
  107. })
  108. } else {
  109. ElMessage({
  110. message: error.message,
  111. type: 'error',
  112. duration: 5 * 1000,
  113. })
  114. }
  115. return Promise.reject(error)
  116. }
  117. )
  118. export function axiosReq({
  119. url,
  120. data,
  121. method,
  122. headers,
  123. isParams,
  124. bfLoading,
  125. afHLoading,
  126. isUploadFile,
  127. isDownLoadFile,
  128. baseURL,
  129. timeout,
  130. isAlertErrorMsg = true,
  131. }: AxiosConfigTy): any {
  132. return service({
  133. url: url,
  134. method: method ?? 'get',
  135. data: data ?? {},
  136. headers: headers ?? {},
  137. isParams: isParams ?? false,
  138. bfLoading: bfLoading ?? false,
  139. afHLoading: afHLoading ?? true,
  140. isUploadFile: isUploadFile ?? false,
  141. isDownLoadFile: isDownLoadFile ?? false,
  142. isAlertErrorMsg: isAlertErrorMsg,
  143. // baseURL: baseURL ?? import.meta.env.VITE_APP_BASE_URL,
  144. baseURL: baseURL ?? PLATFROM_CONFIG.baseNewUrl,
  145. timeout: timeout ?? 15000,
  146. })
  147. }
  148. export default axiosReq