request.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import ElementUI from 'element-ui'
  2. import axios from 'axios'
  3. import { Message } from 'element-ui'
  4. import store from '@/store'
  5. import { getToken } from '@/utils/auth'
  6. import cleanDeep from 'clean-deep'
  7. // import { Loading } from 'element-ui'
  8. import load from '@/utils/loading'
  9. import router from '@/router/index'
  10. import Vue from 'vue'
  11. const showMessage = Symbol('showMessage')
  12. class DonMessage {
  13. success (options, single = true) {
  14. this[showMessage]('success', options, single)
  15. }
  16. warning (options, single = true) {
  17. this[showMessage]('warning', options, single)
  18. }
  19. info (options, single = true) {
  20. this[showMessage]('info', options, single)
  21. }
  22. error (options, single = true) {
  23. this[showMessage]('error', options, single)
  24. }
  25. [showMessage] (type, options, single) {
  26. if (single) {
  27. // 判断是否已存在Message
  28. if (document.getElementsByClassName('el-message').length === 0) {
  29. Message[type](options)
  30. }
  31. } else {
  32. Message[type](options)
  33. }
  34. }
  35. }
  36. Vue.use(ElementUI)
  37. // 命名根据需要,DonMessage只是在文章中使用
  38. Vue.prototype.$message = new DonMessage()
  39. let vue = new Vue()
  40. // let loading //定义loading变量
  41. // function startLoading () { //使用Element loading-start 方法
  42. // loading = Loading.service({
  43. // lock: true,
  44. // fullscreen: true,
  45. // text: '加载中……',
  46. // background: 'rgba(0, 0, 0, 0.7)'
  47. // })
  48. // }
  49. // function endLoading () {
  50. // //使用Element loading-close 方法
  51. // loading.close();
  52. // }
  53. //那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
  54. //声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
  55. //调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
  56. let needLoadingRequestCount = 0
  57. function showFullScreenLoading () {
  58. if (needLoadingRequestCount === 0) {
  59. load.startLoading()
  60. }
  61. needLoadingRequestCount++
  62. }
  63. function tryHideFullScreenLoading () {
  64. if (needLoadingRequestCount <= 0) return
  65. needLoadingRequestCount--
  66. if (needLoadingRequestCount === 0) {
  67. load.endLoading();
  68. }
  69. }
  70. // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  71. // create an axios instance
  72. const service = axios.create({
  73. baseURL: '', // url = base url + request url
  74. // withCredentials: true, // send cookies when cross-domain requests
  75. timeout: 180000, // request timeout
  76. })
  77. // { fullscreen: true, text: '努力加载中', spinner: 'el-icon-loading' }
  78. // request interceptor
  79. service.interceptors.request.use(
  80. config => {
  81. // do something before request is sent
  82. showFullScreenLoading()
  83. if (store.getters.token) {
  84. // let each request carry token
  85. // ['X-Token'] is a custom headers key
  86. // please modify it according to the actual situation
  87. config.headers['Authorization'] = getToken()
  88. // config.headers['content-type'] = "application/x-www-form-urlencoded"
  89. }
  90. config.params = cleanDeep(config.params)
  91. // params: cleanDeep(options.params),
  92. // console.log(config)
  93. return config
  94. },
  95. error => {
  96. // do something with request error
  97. tryHideFullScreenLoading()
  98. return Promise.reject(error)
  99. }
  100. )
  101. // response interceptor
  102. service.interceptors.response.use(
  103. res => {
  104. //res.code !== 200
  105. if (res.data) {
  106. let data = JSON.parse(JSON.stringify(res.data))
  107. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  108. if (data.code == 401 || data.code == 403) {
  109. // Message({
  110. // message: `登录过期,请重新登录!`,
  111. // type: 'error',
  112. // duration: 5 * 1000
  113. // })
  114. vue.$message.error(`登录过期,请重新登录!`)
  115. setTimeout(() => {
  116. tryHideFullScreenLoading()
  117. store.dispatch('user/resetToken').then(() => {
  118. location.reload()
  119. })
  120. }, 1000);
  121. return;
  122. }
  123. if (data.code == 404) {
  124. router.push('/404')
  125. }
  126. if (data.code != 200) {
  127. // Message({
  128. // message: data.msg || `请求失败code码为${ data.code }`,
  129. // type: 'error',
  130. // duration: 5 * 1000
  131. // })
  132. let str = data.msg || `请求失败code码为${data.code}`
  133. vue.$message.error(str)
  134. tryHideFullScreenLoading()
  135. return Promise.reject(new Error(data.msg || 'Error'))
  136. } else {
  137. tryHideFullScreenLoading()
  138. return data
  139. }
  140. } else {
  141. tryHideFullScreenLoading()
  142. return Promise.reject()
  143. }
  144. },
  145. error => {
  146. if (error.message == 'Network Error') {
  147. vue.$message.error('网络异常,请检查网络连接')
  148. } else {
  149. vue.$message.error(error.message)
  150. }
  151. tryHideFullScreenLoading()
  152. return Promise.reject(error)
  153. }
  154. )
  155. export default service