request.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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. // 是否需要设置 token
  43. const isToken = (config.headers || {}).isToken === false
  44. if (getToken() && !isToken) {
  45. config.headers['Authorization'] = 'Bearer ' + getToken()
  46. }
  47. // get请求映射params参数
  48. if (config.method === 'get' && config.params) {
  49. let url = config.url + '?' + tansParams(config.params)
  50. url = url.slice(0, -1)
  51. config.params = {}
  52. config.url = url
  53. }
  54. return config
  55. },
  56. error => {
  57. return Promise.reject(error)
  58. }
  59. )
  60. instance.interceptors.response.use(
  61. response => {
  62. removePending(response.config)
  63. const code = response.data.code || 200
  64. const message = errorCode[code] || response.data.msg || errorCode['default']
  65. if (code === 401) {
  66. MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', {
  67. confirmButtonText: '重新登录',
  68. cancelButtonText: '取消',
  69. type: 'warning'
  70. }).then(() => {
  71. store.dispatch('LogOut').then(() => {
  72. location.href = '/index'
  73. })
  74. })
  75. } else if (code !== 200) {
  76. notifi({ message, type: 'error' })
  77. }
  78. return response.data
  79. },
  80. error => {
  81. console.log(error)
  82. let { message } = error
  83. if (message == 'Network Error') {
  84. message = '后端接口连接异常'
  85. } else if (message.includes('timeout')) {
  86. message = '系统接口请求超时'
  87. } else if (message.includes('Request failed with status code')) {
  88. message = '系统接口' + message.substr(message.length - 3) + '异常'
  89. } else if (message.includes('repeat')) {
  90. message = '操作太频繁,请稍后再试'
  91. } else {
  92. message = '系统错误,请联系管理员'
  93. }
  94. notifi({ message, type: 'error' })
  95. return { code: 0 }
  96. }
  97. )
  98. function tansParams(params) {
  99. let result = ''
  100. for (const propName of Object.keys(params)) {
  101. const value = params[propName]
  102. var part = encodeURIComponent(propName) + '='
  103. if (value !== null && typeof value !== 'undefined') {
  104. if (typeof value === 'object') {
  105. for (const key of Object.keys(value)) {
  106. if (value[key] !== null && typeof value[key] !== 'undefined') {
  107. let params = propName + '[' + key + ']'
  108. var subPart = encodeURIComponent(params) + '='
  109. result += subPart + encodeURIComponent(value[key]) + '&'
  110. }
  111. }
  112. } else {
  113. result += part + encodeURIComponent(value) + '&'
  114. }
  115. }
  116. }
  117. return result
  118. }
  119. // 通用下载方法
  120. export function download(url, params, filename) {
  121. downloadLoadingInstance = Loading.service({ text: '正在下载数据,请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
  122. return instance
  123. .post(url, params, {
  124. transformRequest: [
  125. params => {
  126. return tansParams(params)
  127. }
  128. ],
  129. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  130. responseType: 'blob'
  131. })
  132. .then(async data => {
  133. const isLogin = await blobValidate(data)
  134. if (isLogin) {
  135. const blob = new Blob([data])
  136. saveAs(blob, filename)
  137. } else {
  138. notifi({ message: '无效的会话,或者会话已过期,请重新登录。', type: 'error' })
  139. }
  140. downloadLoadingInstance.close()
  141. })
  142. .catch(r => {
  143. console.error(r)
  144. notifi({ message: '下载文件出现错误,请联系管理员!', type: 'error' })
  145. downloadLoadingInstance.close()
  146. })
  147. }
  148. export default instance