管理系统PC端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

158 lines
5.9 KiB

  1. import axios from 'axios'
  2. import { Notification, MessageBox, Message, Loading } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import errorCode from '@/utils/errorCode'
  6. import { tansParams, blobValidate } from "@/utils/ruoyi"
  7. import cache from '@/plugins/cache'
  8. import { saveAs } from 'file-saver'
  9. let downloadLoadingInstance
  10. // 是否显示重新登录
  11. export let isRelogin = { show: false }
  12. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  13. // 创建axios实例
  14. const service = axios.create({
  15. // axios中请求配置有baseURL选项,表示请求URL公共部分
  16. baseURL: process.env.VUE_APP_BASE_API,
  17. // 超时
  18. timeout: 10000
  19. })
  20. // request拦截器
  21. service.interceptors.request.use(config => {
  22. // 是否需要设置 token
  23. const isToken = (config.headers || {}).isToken === false
  24. // 是否需要防止数据重复提交
  25. const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
  26. if (getToken() && !isToken) {
  27. config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  28. }
  29. // get请求映射params参数
  30. if (config.method === 'get' && config.params) {
  31. let url = config.url + '?' + tansParams(config.params)
  32. url = url.slice(0, -1)
  33. config.params = {}
  34. config.url = url
  35. }
  36. if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
  37. const requestObj = {
  38. url: config.url,
  39. data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
  40. time: new Date().getTime()
  41. }
  42. const requestSize = Object.keys(JSON.stringify(requestObj)).length // 请求数据大小
  43. const limitSize = 5 * 1024 * 1024 // 限制存放数据5M
  44. if (requestSize >= limitSize) {
  45. console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制,无法进行防重复提交验证。')
  46. return config
  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. }, error => {
  67. console.log(error)
  68. Promise.reject(error)
  69. })
  70. // 响应拦截器
  71. service.interceptors.response.use(res => {
  72. // 未设置状态码则默认成功状态
  73. const code = res.data.code || 200
  74. // 获取错误信息
  75. const msg = errorCode[code] || res.data.msg || errorCode['default']
  76. // 二进制数据则直接返回
  77. if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
  78. return res.data
  79. }
  80. console.log(location)
  81. if (code === 401) {
  82. if (!isRelogin.show) {
  83. isRelogin.show = true
  84. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
  85. isRelogin.show = false
  86. store.dispatch('LogOut').then(() => {
  87. if (location.pathname.indexOf('/app/') > -1){
  88. location.href = '/app/index'
  89. }else{
  90. location.href = '/index'
  91. }
  92. })
  93. }).catch(() => {
  94. isRelogin.show = false
  95. })
  96. }
  97. return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
  98. } else if (code === 500) {
  99. Message({ message: msg, type: 'error' })
  100. return Promise.reject(new Error(msg))
  101. } else if (code === 601) {
  102. Message({ message: msg, type: 'warning' })
  103. return Promise.reject('error')
  104. } else if (code !== 200) {
  105. Notification.error({ title: msg })
  106. return Promise.reject('error')
  107. } else {
  108. return res.data
  109. }
  110. },
  111. error => {
  112. console.log('err' + error)
  113. let { message } = error
  114. if (message == "Network Error") {
  115. message = "后端接口连接异常"
  116. } else if (message.includes("timeout")) {
  117. message = "系统接口请求超时"
  118. } else if (message.includes("Request failed with status code")) {
  119. message = "系统接口" + message.substr(message.length - 3) + "异常"
  120. }
  121. Message({ message: message, type: 'error', duration: 5 * 1000 })
  122. return Promise.reject(error)
  123. }
  124. )
  125. // 通用下载方法
  126. export function download(url, params, filename, config) {
  127. downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  128. return service.post(url, params, {
  129. transformRequest: [(params) => { return tansParams(params) }],
  130. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  131. responseType: 'blob',
  132. ...config
  133. }).then(async (data) => {
  134. const isBlob = blobValidate(data)
  135. if (isBlob) {
  136. const blob = new Blob([data])
  137. saveAs(blob, filename)
  138. } else {
  139. const resText = await data.text()
  140. const rspObj = JSON.parse(resText)
  141. const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  142. Message.error(errMsg)
  143. }
  144. downloadLoadingInstance.close()
  145. }).catch((r) => {
  146. console.error(r)
  147. Message.error('下载文件出现错误,请联系管理员!')
  148. downloadLoadingInstance.close()
  149. })
  150. }
  151. export default service