request.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import axios from 'axios'
  2. import Qs from 'qs'
  3. import {modal} from '@/components/common/modal'
  4. import contants from '@/scripts/contants.js'
  5. import bus from '@/scripts/bus.js'
  6. const config = {
  7. // 请求路径
  8. baseURL: '',
  9. // 默认请求方法
  10. method: 'post',
  11. // 请求超时时间(毫秒)
  12. timeout: 0,
  13. // 是否携带cookie信息
  14. withCredentials: true,
  15. // 响应格式,可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  16. responseType: 'json',
  17. // 自定义添加头部
  18. headers: {
  19. // ;charset=UTF-8
  20. 'Content-Type': 'application/x-www-form-urlencoded'
  21. },
  22. // `transformRequest` 允许在向服务器发送前,修改请求数据
  23. // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  24. // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
  25. transformRequest: [
  26. function (data) {
  27. if(data instanceof FormData){
  28. return data;
  29. }
  30. return Qs.stringify(data, {
  31. // a:[1,2] => a=1&a=2
  32. arrayFormat: 'repeat',
  33. // a[b]:1 => a.b=1
  34. allowDots: true
  35. })
  36. }
  37. ],
  38. paramsSerializer(data) {
  39. return Qs.stringify(data, {
  40. // a:[1,2] => a=1&a=2
  41. arrayFormat: 'repeat',
  42. // a[b]:1 => a.b=1
  43. allowDots: true
  44. })
  45. }
  46. }
  47. class HttpResponse {
  48. // 请求成功调用 code == 1的
  49. successHandle = null
  50. // 请求异常,包含js异常调用
  51. errorHandle = null
  52. endHandle = null
  53. constructor() {
  54. }
  55. // 异常回调,实际上的code != 1的
  56. exceptionHandle = (code, message) => {
  57. modal.magicAlert({
  58. title: `请求出错,异常代码(${code})`,
  59. content: message
  60. })
  61. }
  62. // 调用返回成功需要注入的变量
  63. success(handle) {
  64. this.successHandle = handle
  65. return this
  66. }
  67. exception(handle) {
  68. this.exceptionHandle = handle
  69. return this
  70. }
  71. // 调用异常需要注入的变量
  72. error(handle) {
  73. this.errorHandle = handle
  74. return this
  75. }
  76. end(handle) {
  77. this.endHandle = handle;
  78. }
  79. }
  80. class HttpRequest {
  81. _axios = null
  82. constructor() {
  83. this._axios = axios.create(config)
  84. }
  85. // 返回初始化过后的axios
  86. getAxios() {
  87. return this._axios
  88. }
  89. setBaseURL(baseURL) {
  90. config.baseURL = baseURL
  91. }
  92. execute(requestConfig) {
  93. let _config = {
  94. baseURL: config.baseURL,
  95. ...requestConfig
  96. }
  97. _config.headers = _config.headers || {};
  98. _config.headers[contants.HEADER_MAGIC_TOKEN] = contants.HEADER_MAGIC_TOKEN_VALUE
  99. return this._axios.request(_config);
  100. }
  101. processError(error) {
  102. if (error.response) {
  103. modal.magicAlert({
  104. title: `请求出错HttpStatus:(${error.response.status})`,
  105. content: JSON.stringify(error.response.data || '') || `请求出错HttpStatus:(${error.response.status})`
  106. })
  107. } else {
  108. modal.magicAlert({
  109. title: `请求出错`,
  110. content: error.message
  111. })
  112. }
  113. console.error(error)
  114. }
  115. // 发送默认请求
  116. send(url, params, newConfig) {
  117. let requestConfig = newConfig || config || {}
  118. requestConfig.url = url
  119. if (requestConfig.method === 'post') {
  120. requestConfig.data = params
  121. } else {
  122. requestConfig.params = params
  123. }
  124. requestConfig.baseURL = config.baseURL
  125. let httpResponse = new HttpResponse()
  126. let successed = false;
  127. this.execute(requestConfig)
  128. .then(response => {
  129. let data = response.data
  130. if(data instanceof Blob){
  131. successed = true
  132. httpResponse.successHandle && httpResponse.successHandle(data, response)
  133. } else if (data.code === 1) {
  134. successed = true
  135. httpResponse.successHandle && httpResponse.successHandle(data.data, response)
  136. } else {
  137. if (data.code === 401) {
  138. bus.$emit('showLogin')
  139. }
  140. httpResponse.exceptionHandle && httpResponse.exceptionHandle(data.code, data.message, response)
  141. }
  142. })
  143. .catch((error) => {
  144. if (typeof httpResponse.errorHandle === 'function') {
  145. httpResponse.errorHandle(error.response.data, error.response, error)
  146. } else {
  147. this.processError(error)
  148. }
  149. })
  150. .finally(() => {
  151. if (typeof httpResponse.endHandle === 'function') {
  152. httpResponse.endHandle(successed)
  153. }
  154. })
  155. return httpResponse
  156. }
  157. }
  158. export default new HttpRequest()