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