index.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import http from './interface'
  2. import { platform } from '../utils/index'
  3. import { webLogin, mini_env, replaceStringInObject } from '@/common/utils/util'
  4. import store from '@/store/index.js'
  5. import { goLoginPage } from '@/mixins/index.js'
  6. import { setStorage, getStorage, removeStorage } from '@/common/utils/storage.js'
  7. import { navToPage } from 'common/utils/navPag'
  8. // #ifdef H5
  9. // 解析地址栏参数
  10. function getQueryVariable(variable) {
  11. // 从?开始获取后面的所有数据
  12. var query = window.location.search.substring(1)
  13. // 从字符串&开始分隔成数组split
  14. var vars = query.split('&')
  15. // 遍历该数组
  16. for (var i = 0; i < vars.length; i++) {
  17. // 从等号部分分割成字符
  18. var pair = vars[i].split('=')
  19. // 如果第一个元素等于 传进来的参的话 就输出第二个元素
  20. if (pair[0] == variable) {
  21. return pair[1]
  22. }
  23. }
  24. return undefined
  25. }
  26. // #endif
  27. const program = {
  28. H5: 'wap',
  29. APP: 'app',
  30. APPNVUE: 'app',
  31. WEIXIN: 'miniProgram'
  32. }
  33. const whiteCodes = [200, 201]
  34. function removeQueryParams(params) {
  35. var url = new URL(window.location.href) // 获取当前 URL
  36. // 遍历每个参数并删除
  37. params.forEach(function (param) {
  38. url.searchParams.delete(param)
  39. })
  40. // 使用新的 URL 更新地址栏,且不刷新页面
  41. window.history.pushState({}, '', url)
  42. location.reload() // 刷新页面,重新加载
  43. }
  44. export const $http = (url, method, data, json, loadingBool = false, isExecute = true, isForm = false) => {
  45. //设置请求前拦截器
  46. http.interceptor.request = config => {
  47. return new Promise(r => {
  48. mini_env(bool => {
  49. if (loadingBool && url !== '/homepage/study') {
  50. uni.showLoading({
  51. title: '加载中...'
  52. })
  53. }
  54. config.header = {
  55. 'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
  56. // "x-token": getStorage('token'),
  57. 'x-token': store.getters.token,
  58. APPID: store.getters.appId,
  59. Program: program[platform()],
  60. source: bool ? 'A' : 'B',
  61. miniOpenId: store.getters.miniOpenId,
  62. sharerOpenId: store.getters.sharerOpenId
  63. }
  64. r(true)
  65. })
  66. })
  67. }
  68. //设置请求结束后拦截器
  69. http.interceptor.response = async response => {
  70. //判断返回状态 执行相应操作
  71. if (loadingBool) {
  72. uni.hideLoading()
  73. }
  74. const res = replaceStringInObject(
  75. response.data || {},
  76. ['https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/', 'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/'],
  77. process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/img/get?key='
  78. )
  79. if (!isExecute) {
  80. return res
  81. }
  82. if (whiteCodes.indexOf(res.code) < 0) {
  83. if (~res.message.indexOf('USERPAYING')) {
  84. return Promise.reject(new Error(res.message || 'Error'))
  85. }
  86. // if (res.code === 4444) {
  87. // // #ifdef H5
  88. // uni.removeStorageSync(`APPID${getQueryVariable('appid')}_token`)
  89. // // #endif
  90. // webLogin(true)
  91. // return {}
  92. // }
  93. if (res.code === 1001) {
  94. webLogin(true)
  95. return {}
  96. } else if (res.code === 4001) {
  97. uni.showModal({
  98. title: '提示',
  99. content: '你尚未绑定手机号,无法下单!',
  100. confirmText: '立即绑定',
  101. success: function (res) {
  102. if (res.confirm) {
  103. navToPage({
  104. url: '/packageMine/pages/phone'
  105. })
  106. } else if (res.cancel) {
  107. console.log('用户点击取消')
  108. }
  109. }
  110. })
  111. } else {
  112. if (isForm) {
  113. uni.showModal({
  114. title: '温馨提示',
  115. content: res.message || 'Error',
  116. showCancel: false,
  117. success: function (res) {
  118. if (res.confirm) {
  119. } else if (res.cancel) {
  120. }
  121. }
  122. })
  123. } else {
  124. uni.showModal({
  125. title: '温馨提示',
  126. content: res.message || 'Error',
  127. showCancel: false,
  128. confirmText: '知道了',
  129. success: function (res) {
  130. if (res.confirm) {
  131. } else if (res.cancel) {
  132. }
  133. }
  134. })
  135. }
  136. }
  137. return Promise.reject(new Error(res.message || 'Error'))
  138. } else {
  139. return res
  140. }
  141. }
  142. if (store.getters.token) {
  143. return http.request({
  144. method: method,
  145. url: url,
  146. dataType: 'json',
  147. data
  148. })
  149. } else if (!!~['/user/auth2', '/goods/detail'].indexOf(url)) {
  150. return http.request({
  151. method: method,
  152. url: url,
  153. dataType: 'json',
  154. data
  155. })
  156. } else {
  157. return new Promise((resolve, reject) => {
  158. var i = 0
  159. var digui = function () {
  160. i++
  161. if ((store?.getters?.token && store?.getters?.userId) || i == 300) {
  162. http
  163. .request({
  164. method: method,
  165. url: url,
  166. dataType: 'json',
  167. data: {
  168. ...data,
  169. userId: store.getters.userId
  170. }
  171. })
  172. .then(resolve)
  173. .catch(reject)
  174. } else {
  175. setTimeout(digui, 100)
  176. }
  177. }
  178. digui()
  179. })
  180. }
  181. }
  182. async function login() {
  183. //返回环宇token所需的login code
  184. return new Promise(resolve => {
  185. uni.login({
  186. provider: 'weixin',
  187. success(loginRes) {
  188. resolve(loginRes.code)
  189. },
  190. fail() {}
  191. })
  192. })
  193. }
  194. async function doRequest(response, url) {
  195. var code = await login()
  196. var res = await get('/v1/oauth/refreshToken/code/' + code, {})
  197. if (res && res.data.data.token) {
  198. let config = response.config
  199. setStorage('token', res.data.data.token)
  200. config.header['Authorization'] = res.data.data.token
  201. let json = config.header['Content-Type'] === 'application/json'
  202. const resold = await $http(
  203. url,
  204. config.method,
  205. {
  206. ...config.data
  207. },
  208. json
  209. )
  210. return resold
  211. } else {
  212. uni.clearStorage()
  213. uni.showToast({
  214. title: '授权失效,请重新登录',
  215. duration: 1000
  216. })
  217. this.$navToPage({
  218. url: '/pages/login/auth'
  219. })
  220. return false
  221. }
  222. }
  223. function postJson(url, data, loadingBool, isExecute, isForm) {
  224. return $http(url, 'POST', data, true, loadingBool, isExecute, isForm)
  225. }
  226. function post(url, data, loadingBool, isExecute, isForm) {
  227. return $http(url, 'POST', data, false, loadingBool, isExecute, isForm)
  228. }
  229. function get(url, data, loadingBool) {
  230. return $http(url, 'GET', data, false, loadingBool)
  231. }
  232. function put(url, data, loadingBool) {
  233. return $http(url, 'PUT', data, true, loadingBool)
  234. }
  235. function del(url, data, loadingBool) {
  236. return $http(url, 'DELETE', data, true, loadingBool)
  237. }
  238. //封装的通用请求方法
  239. export const axios = function (obj = {}) {
  240. if (typeof obj !== 'object') {
  241. throw new Error('arguments must be object')
  242. }
  243. if (!obj.url) {
  244. throw new Error('url not defined')
  245. }
  246. return new Promise((resolve, reject) => {
  247. if (obj.isLoading) {
  248. uni.showLoading({
  249. title: '加载中',
  250. mask: true
  251. })
  252. }
  253. let _url = process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + obj.url
  254. let isGet = obj.method && obj.method.toLowerCase() == 'get'
  255. let isQuery = obj.isQuery
  256. if (isGet || isQuery) {
  257. _url +=
  258. '?' +
  259. Object.entries(obj.params || {})
  260. .map(item => item.join('='))
  261. .join('&')
  262. }
  263. let _type = 'application/x-www-form-urlencoded'
  264. if (obj.type == 'json') {
  265. _type = 'application/json'
  266. }
  267. uni.request({
  268. url: _url,
  269. data: isGet || isQuery ? '' : obj.params || '',
  270. header: {
  271. 'content-type': _type,
  272. 'x-token': store.getters.token
  273. },
  274. method: obj.method ? obj.method : 'POST',
  275. success: function (ress) {
  276. if (obj.isLoading) {
  277. uni.hideLoading()
  278. }
  279. const res = replaceStringInObject(
  280. ress.data,
  281. ['https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/', 'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/'],
  282. process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/img/get?key='
  283. )
  284. if (whiteCodes.indexOf(res.code) < 0) {
  285. if (res.code === 1001) {
  286. webLogin(true)
  287. reject(new Error(res.message || 'Error'))
  288. return {}
  289. }
  290. // if (res.code === 4444) {
  291. // // #ifdef H5
  292. // uni.removeStorageSync(`APPID${getQueryVariable('appid')}_token`)
  293. // // #endif
  294. // webLogin(true)
  295. // reject(new Error(res.message || 'Error'))
  296. // return {}
  297. // }
  298. if (res.message || res.code) {
  299. uni.showToast({
  300. title: res.message || 'Error',
  301. icon: 'none',
  302. duration: 1500
  303. })
  304. }
  305. reject(new Error(res.message || 'Error'))
  306. } else {
  307. resolve(res)
  308. }
  309. },
  310. fail: function (err) {
  311. uni.hideLoading()
  312. uni.showModal({
  313. title: '提示',
  314. content: '网络连接失败' + JSON.stringify(err)
  315. })
  316. reject(err)
  317. }
  318. })
  319. })
  320. }
  321. export default {
  322. postJson,
  323. get,
  324. post,
  325. put,
  326. del
  327. }