request.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import axios from 'axios'
  2. import {
  3. baseURL,
  4. contentType,
  5. messageName,
  6. requestTimeout,
  7. statusName,
  8. successCode,
  9. } from '@/config/net.config'
  10. // import router from '@/router'
  11. import configpath from 'config/setting.config.js'
  12. let baseURL1 = ''
  13. let isAction, isDataAll;
  14. const inforeq = (cb) => {
  15. fetch('/static/.config.json')
  16. .then((res) =>res = res.json()).then((res)=>{
  17. let obj = {
  18. ...res,
  19. img_local_host: (process.env.NODE_ENV === 'production' ?
  20. res.prodIp || configpath.prodIp :
  21. process.env.NODE_ENV === 'test' ?
  22. res.testIp || configpath.testIp :
  23. res.devIp || configpath.devIp) + '/file/',
  24. // 请求 地址
  25. baseURL: (process.env.NODE_ENV === 'production' ?
  26. res.prodIp || configpath.prodIp :
  27. process.env.NODE_ENV === 'test' ?
  28. res.testIp || configpath.testIp :
  29. res.devIp || configpath.devIp) + '/api/h5',
  30. }
  31. baseURL1 = obj.baseURL
  32. cb && cb()
  33. })
  34. }
  35. inforeq()
  36. /**
  37. * axios响应拦截器
  38. * @param data response数据
  39. * @param status HTTP status
  40. * @param statusText HTTP status text
  41. * @returns {Promise<*|*>}
  42. */
  43. const handleData = async ({
  44. config,
  45. data,
  46. status,
  47. statusText
  48. }) => {
  49. // 若data.code存在,覆盖默认code
  50. let code = data && data[statusName] ? data[statusName] : status
  51. // 若code属于操作正常code,则status修改为200
  52. switch (code) {
  53. case 200:
  54. // 业务层级错误处理,以下是假定restful有一套统一输出格式(指不管成功与否都有相应的数据格式)情况下进行处理
  55. // 例如响应内容:
  56. // 错误内容:{ code: 1, msg: '非法参数' }
  57. // 正确内容:{ code: 200, data: { }, msg: '操作正常' }
  58. // return data
  59. // if (isAction)
  60. // Vue.prototype.$baseNotify(
  61. // data[messageName],
  62. // '消息提示',
  63. // )
  64. return data
  65. case 401:
  66. // store
  67. // .dispatch('user/resetAll')
  68. // .then(() =>
  69. // router.push({ path: '/login', replace: true }).then(() => { })
  70. // )
  71. break
  72. case 403:
  73. // router.push({ path: '/403' }).then(() => { })
  74. break
  75. }
  76. if (isDataAll) {
  77. return data
  78. }
  79. // 异常处理
  80. // 若data.msg存在,覆盖默认提醒消息
  81. // const errMsg = `${data && data[messageName]
  82. // ? data[messageName]
  83. // : CODE_MESSAGE[code]
  84. // ? CODE_MESSAGE[code]
  85. // : statusText
  86. // }`
  87. // console.log(data)
  88. return Promise.reject(data)
  89. }
  90. /**
  91. * @description axios初始化
  92. */
  93. const instance = axios.create({
  94. baseURL,
  95. timeout: requestTimeout,
  96. headers: {
  97. 'Content-Type': contentType,
  98. },
  99. })
  100. let pendingMap = new Map();
  101. let removePending = function(config) {
  102. var key = `${config.method}:${config.url}:${JSON.stringify(config.params)}`;
  103. var func = pendingMap.get(key);
  104. if (func) {
  105. func();
  106. pendingMap.delete(key);
  107. }
  108. }
  109. /**
  110. * @description axios请求拦截器
  111. */
  112. instance.interceptors.request.use(
  113. (config) => {
  114. config.baseURL = baseURL1
  115. // const token = store.getters['user/token']
  116. // config.baseURL = store.getters['user/locationpath'].baseURL
  117. removePending(config);
  118. // 发送请求,并将请求的取消标识放入pendingMap中
  119. config.cancelToken = new axios.CancelToken((cancelToken) => {
  120. pendingMap.set(`${config.method}:${config.url}:${JSON.stringify(config.params)}`, cancelToken)
  121. });
  122. // 规范写法 不可随意自定义
  123. // if (token) config.headers['token'] = token
  124. if (
  125. config.data &&
  126. config.headers['Content-Type'] ===
  127. 'application/x-www-form-urlencoded;charset=UTF-8'
  128. )
  129. config.data = JSON.stringify(config.data)
  130. isAction = config.isAction
  131. isDataAll = config.isDataAll
  132. return config
  133. },
  134. (error) => {
  135. return Promise.reject(error)
  136. }
  137. )
  138. /**
  139. * @description axios响应拦截器
  140. */
  141. let url = '',
  142. path1 = ''
  143. instance.interceptors.response.use(
  144. (response) => {
  145. const config = response.config
  146. url = `${config.method}:${config.url}:${JSON.stringify(config.params)}`;
  147. path1 = config.url
  148. return handleData(response)
  149. },
  150. (error) => {
  151. const {
  152. response
  153. } = error
  154. // console.log(response)
  155. if (response === undefined) {
  156. if (path1 !== '/eye/save_hand_img') {
  157. // Vue.prototype.$baseMessage(
  158. // '网络错误',
  159. // 'error',
  160. // 'vab-hey-message-error'
  161. // )
  162. } else {
  163. pendingMap.delete(key);
  164. }
  165. return Promise.reject({
  166. code: -1
  167. })
  168. } else return handleData(response)
  169. }
  170. )
  171. export default instance