micro_request.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import axios from 'axios'
  2. import errorCode from '@/utils/errorCode'
  3. axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
  4. const service = axios.create({
  5. // axios中请求配置有baseURL选项,表示请求URL公共部分
  6. baseURL: process.uniEnv.VUE_APP_MicroSrvProxy_API,
  7. // 超时
  8. timeout: 60000,
  9. })
  10. // request拦截器
  11. service.interceptors.request.use(
  12. (config) => {
  13. config.headers['Tenant'] = process.uniEnv.VUE_APP_TENANT
  14. // 是否需要设置 token
  15. const isToken = (config.headers || {}).isToken === false
  16. if (uni.getStorageSync('opms_token') && !isToken) {
  17. config.headers['Authorization'] = 'Bearer ' + uni.getStorageSync('opms_token') // 让每个请求携带自定义token 请根据实际情况自行修改
  18. }
  19. return config
  20. },
  21. (error) => {
  22. Promise.reject(error)
  23. }
  24. )
  25. // 响应拦截器
  26. service.interceptors.response.use(
  27. (res) => {
  28. if (res.request && res.request.responseType == 'blob') {
  29. // 判断是否是文件流
  30. let fileReader = new FileReader()
  31. fileReader.readAsText(res.data)
  32. fileReader.onload = function () {
  33. try {
  34. let jsonData = JSON.parse(this.result) // 解析成功说明是普通对象数据,后端返回的是文件上传的错误信息
  35. res.data = jsonData
  36. processResponse(res)
  37. return
  38. } catch (err) {
  39. // 解析成对象失败,说明是文件流
  40. downLoadBlobFile(res)
  41. return
  42. }
  43. }
  44. }
  45. // 常规响应处理
  46. return processResponse(res)
  47. },
  48. (error) => {
  49. uni.showToast({
  50. title: error.message,
  51. icon: 'none',
  52. duration: 5 * 1000,
  53. })
  54. return Promise.reject(error)
  55. }
  56. )
  57. service.postRequest = function postRequest(basePath, srvName, funcName, data) {
  58. if (data == undefined) {
  59. let nullParam = {
  60. nullparam: 0,
  61. }
  62. data = nullParam
  63. }
  64. var base_Path = ''
  65. if (basePath == process.uniEnv.VUE_APP_FOSHAN_PATH) {
  66. base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_foshan_API + basePath
  67. } else if (basePath == process.uniEnv.VUE_APP_AdminPath || process.uniEnv.VUE_APP_ParentPath) {
  68. base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  69. } else {
  70. base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  71. }
  72. return service.request({
  73. url: base_Path,
  74. method: 'post',
  75. headers: {
  76. 'Content-Type': 'application/rpcx',
  77. 'X-RPCX-SerializeType': '1',
  78. 'X-RPCX-ServicePath': srvName,
  79. 'X-RPCX-ServiceMethod': funcName,
  80. SrvEnv: 'dev',
  81. },
  82. data: data,
  83. })
  84. }
  85. // 发出请求并要求把客户端信息传输给后端(IP和User-Agent)
  86. service.postRequestWithClientInfo = function postRequest(basePath, srvName, funcName, data) {
  87. if (data == undefined) {
  88. let nullParam = { nullparam: 0 }
  89. data = nullParam
  90. }
  91. return service.request({
  92. url: basePath,
  93. method: 'post',
  94. headers: {
  95. 'Content-Type': 'application/rpcx',
  96. 'X-RPCX-SerializeType': '1',
  97. 'X-RPCX-ServicePath': srvName,
  98. 'X-RPCX-ServiceMethod': funcName,
  99. 'X-RPCX-Meta': 'need_clint_Info=1',
  100. },
  101. data: data,
  102. })
  103. }
  104. // Excel文件下载(服务端生成文件流)
  105. service.downloadExcel = function downloadExcel(basePath, srvName, funcName, data) {
  106. if (data == undefined) {
  107. let nullParam = {
  108. nullparam: 0,
  109. }
  110. data = nullParam
  111. }
  112. var base_Path = ''
  113. if (basePath == process.uniEnv.VUE_APP_AdminPath) {
  114. base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  115. } else if (basePath == process.uniEnv.VUE_APP_ParentPath) {
  116. base_Path = process.uniEnv.VUE_APP_MicroSrvProxy_API + basePath
  117. }
  118. service.request({
  119. url: base_Path,
  120. method: 'post',
  121. responseType: 'blob',
  122. headers: {
  123. 'Content-Type': 'application/rpcx',
  124. 'X-RPCX-SerializeType': '1',
  125. 'X-RPCX-ServicePath': srvName,
  126. 'X-RPCX-ServiceMethod': funcName,
  127. },
  128. data: data,
  129. })
  130. }
  131. axios.defaults.adapter = function (config) {
  132. return new Promise((resolve, reject) => {
  133. var settle = require('axios/lib/core/settle')
  134. var buildURL = require('axios/lib/helpers/buildURL')
  135. uni.request({
  136. method: config.method.toUpperCase(),
  137. url: buildURL(config.url, config.params, config.paramsSerializer),
  138. header: config.headers,
  139. data: config.data,
  140. dataType: config.dataType,
  141. responseType: config.responseType,
  142. sslVerify: config.sslVerify,
  143. complete: function complete(response) {
  144. response = {
  145. data: response.data,
  146. status: response.statusCode,
  147. errMsg: response.errMsg,
  148. header: response.header,
  149. config: config,
  150. }
  151. settle(resolve, reject, response)
  152. },
  153. })
  154. })
  155. }
  156. function processResponse(res) {
  157. // 未设置状态码则默认成功状态
  158. const code = res.data.code || 200
  159. // 获取错误信息
  160. const message = errorCode[code] || res.data.msg || errorCode['default']
  161. if (code === 1010 || code === 1011) {
  162. uni.showToast({
  163. title: message,
  164. icon: 'none',
  165. duration: 3 * 1000,
  166. complete: () => {
  167. uni.reLaunch({
  168. url: '/pages/login/index',
  169. })
  170. },
  171. })
  172. } else if (code === 500) {
  173. uni.showToast({
  174. title: message,
  175. icon: 'none',
  176. duration: 3 * 1000,
  177. })
  178. return Promise.reject(new Error(message))
  179. } else if (code !== 200) {
  180. uni.showToast({
  181. title: message,
  182. icon: 'none',
  183. duration: 3 * 1000,
  184. })
  185. return Promise.reject('error')
  186. } else {
  187. // if (res.data.msg) {
  188. // Message({
  189. // message: res.data.msg,
  190. // type: 'success'
  191. // })
  192. // }
  193. return res.data
  194. }
  195. }
  196. function downLoadBlobFile(res, mimeType) {
  197. if (mimeType == undefined) {
  198. mimeType = 'application/vnd.ms-excel'
  199. }
  200. const aLink = document.createElement('a')
  201. var blob = new Blob([res.data], {
  202. type: mimeType,
  203. })
  204. // //从response的headers中获取filename, 后端response.setHeader('Content-disposition', 'attachment filename=xxxx.docx') 设置的文件名
  205. var patt = new RegExp('filename=([^]+\\.[^\\.]+)*')
  206. var contentDisposition = decodeURI(res.headers['content-disposition'] || res.headers['Content-Disposition'])
  207. var result = patt.exec(contentDisposition)
  208. var fileName = 'data.xlsx'
  209. if (result != undefined) {
  210. fileName = result[1]
  211. fileName = decodeURI(escape(fileName))
  212. fileName = fileName.replace(/'/g, '')
  213. }
  214. aLink.href = URL.createObjectURL(blob)
  215. aLink.setAttribute('download', fileName) // 设置下载文件名称
  216. document.body.appendChild(aLink)
  217. aLink.click()
  218. document.body.appendChild(aLink)
  219. }
  220. export default service