request.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import axios from 'axios'
  2. import { Loading, MessageBox } from 'element-ui'
  3. import notifi from '@/plugins/msg.js'
  4. import store from '@/store'
  5. import { getToken } from '@/utils/auth'
  6. import { blobValidate } from '@/utils/tiegu'
  7. import errorCode from '@/utils/errorCode'
  8. let downloadLoadingInstance
  9. let pending = []
  10. let cancelToken = axios.CancelToken
  11. let removePending = (config) => {
  12. for (let p in pending) {
  13. let key = +p
  14. let item = pending[key]
  15. if (item.url === config.url && item.method === config.method && JSON.stringify(item.params) === JSON.stringify(config.params) && JSON.stringify(item.data) === JSON.stringify(config.data)) {
  16. item.cancel('repeat submission')
  17. pending.splice(item, 1)
  18. }
  19. }
  20. }
  21. // axios 配置
  22. var instance = axios.create({
  23. headers: {
  24. 'Content-Type': 'application/json;charset=UTF-8'
  25. },
  26. timeout: 1000 * 30, //请求超时时间
  27. baseURL: process.env.VUE_APP_BASE_API, //请求默认地址
  28. withCredentials: true //允许请求携带cookie信息
  29. })
  30. instance.interceptors.request.use(
  31. (config) => {
  32. removePending(config)
  33. config.cancelToken = new cancelToken((c) => {
  34. pending.push({
  35. url: config.url,
  36. method: config.method,
  37. params: config.params,
  38. data: config.data,
  39. cancel: c
  40. })
  41. })
  42. if (getToken()) {
  43. config.headers['Authorization'] = 'Bearer ' + getToken()
  44. }
  45. // get请求映射params参数
  46. if (config.method === 'get' && config.params) {
  47. let url = config.url + '?' + tansParams(config.params)
  48. url = url.slice(0, -1)
  49. config.params = {}
  50. config.url = url
  51. }
  52. return config
  53. },
  54. (error) => {
  55. return Promise.reject(error)
  56. }
  57. )
  58. instance.interceptors.response.use(
  59. (response) => {
  60. removePending(response.config)
  61. const code = response.data.code || 200
  62. const message = errorCode[code] || response.data.msg || errorCode['default']
  63. if (code === 401) {
  64. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  65. confirmButtonText: '重新登录',
  66. cancelButtonText: '取消',
  67. type: 'warning'
  68. }).then(() => {
  69. store.dispatch('LogOut').then(() => {
  70. location.href = '/index'
  71. })
  72. })
  73. } else if (code !== 200) {
  74. notifi({ message, type: 'error' })
  75. }
  76. return response.data
  77. },
  78. (error) => {
  79. console.log(error)
  80. let { message } = error
  81. if (message == 'Network Error') {
  82. message = '后端接口连接异常'
  83. } else if (message.includes('timeout')) {
  84. message = '系统接口请求超时'
  85. } else if (message.includes('Request failed with status code')) {
  86. message = '系统接口' + message.substr(message.length - 3) + '异常'
  87. } else if (message.includes('repeat')) {
  88. message = '操作太频繁,请稍后再试'
  89. } else {
  90. message = '系统错误,请联系管理员'
  91. }
  92. notifi({ message, type: 'error' })
  93. return { code: 0 }
  94. }
  95. )
  96. function tansParams(params) {
  97. let result = ''
  98. for (const propName of Object.keys(params)) {
  99. const value = params[propName]
  100. var part = encodeURIComponent(propName) + '='
  101. if (value !== null && typeof value !== 'undefined') {
  102. if (typeof value === 'object') {
  103. for (const key of Object.keys(value)) {
  104. if (value[key] !== null && typeof value[key] !== 'undefined') {
  105. let params = propName + '[' + key + ']'
  106. var subPart = encodeURIComponent(params) + '='
  107. result += subPart + encodeURIComponent(value[key]) + '&'
  108. }
  109. }
  110. } else {
  111. result += part + encodeURIComponent(value) + '&'
  112. }
  113. }
  114. }
  115. return result
  116. }
  117. // 通用下载方法
  118. export function download(url, params, filename) {
  119. downloadLoadingInstance = Loading.service({ text: '正在下载数据,请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  120. return instance
  121. .post(url, params, {
  122. transformRequest: [
  123. (params) => {
  124. return tansParams(params)
  125. }
  126. ],
  127. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  128. responseType: 'blob'
  129. })
  130. .then(async (data) => {
  131. const isLogin = await blobValidate(data)
  132. if (isLogin) {
  133. const blob = new Blob([data])
  134. saveAs(blob, filename)
  135. } else {
  136. notifi({ message: '无效的会话,或者会话已过期,请重新登录。', type: 'error' })
  137. }
  138. downloadLoadingInstance.close()
  139. })
  140. .catch((r) => {
  141. console.error(r)
  142. notifi({ message: '下载文件出现错误,请联系管理员!', type: 'error' })
  143. downloadLoadingInstance.close()
  144. })
  145. }
  146. export default instance