index.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 digui = function () {
  159. if (store?.getters?.token && store?.getters?.userId) {
  160. http
  161. .request({
  162. method: method,
  163. url: url,
  164. dataType: 'json',
  165. data: {
  166. ...data,
  167. userId: store.getters.userId
  168. }
  169. })
  170. .then(resolve)
  171. .catch(reject)
  172. } else {
  173. setTimeout(digui, 100)
  174. }
  175. }
  176. digui()
  177. })
  178. }
  179. }
  180. async function login() {
  181. //返回环宇token所需的login code
  182. return new Promise(resolve => {
  183. uni.login({
  184. provider: 'weixin',
  185. success(loginRes) {
  186. resolve(loginRes.code)
  187. },
  188. fail() {}
  189. })
  190. })
  191. }
  192. async function doRequest(response, url) {
  193. var code = await login()
  194. var res = await get('/v1/oauth/refreshToken/code/' + code, {})
  195. if (res && res.data.data.token) {
  196. let config = response.config
  197. setStorage('token', res.data.data.token)
  198. config.header['Authorization'] = res.data.data.token
  199. let json = config.header['Content-Type'] === 'application/json'
  200. const resold = await $http(
  201. url,
  202. config.method,
  203. {
  204. ...config.data
  205. },
  206. json
  207. )
  208. return resold
  209. } else {
  210. uni.clearStorage()
  211. uni.showToast({
  212. title: '授权失效,请重新登录',
  213. duration: 1000
  214. })
  215. this.$navToPage({
  216. url: '/pages/login/auth'
  217. })
  218. return false
  219. }
  220. }
  221. function postJson(url, data, loadingBool, isExecute, isForm) {
  222. return $http(url, 'POST', data, true, loadingBool, isExecute, isForm)
  223. }
  224. function post(url, data, loadingBool, isExecute, isForm) {
  225. return $http(url, 'POST', data, false, loadingBool, isExecute, isForm)
  226. }
  227. function get(url, data, loadingBool) {
  228. return $http(url, 'GET', data, false, loadingBool)
  229. }
  230. function put(url, data, loadingBool) {
  231. return $http(url, 'PUT', data, true, loadingBool)
  232. }
  233. function del(url, data, loadingBool) {
  234. return $http(url, 'DELETE', data, true, loadingBool)
  235. }
  236. //封装的通用请求方法
  237. export const axios = function (obj = {}) {
  238. if (typeof obj !== 'object') {
  239. throw new Error('arguments must be object')
  240. }
  241. if (!obj.url) {
  242. throw new Error('url not defined')
  243. }
  244. return new Promise((resolve, reject) => {
  245. if (obj.isLoading) {
  246. uni.showLoading({
  247. title: '加载中',
  248. mask: true
  249. })
  250. }
  251. let _url = process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + obj.url
  252. let isGet = obj.method && obj.method.toLowerCase() == 'get'
  253. let isQuery = obj.isQuery
  254. if (isGet || isQuery) {
  255. _url +=
  256. '?' +
  257. Object.entries(obj.params || {})
  258. .map(item => item.join('='))
  259. .join('&')
  260. }
  261. let _type = 'application/x-www-form-urlencoded'
  262. if (obj.type == 'json') {
  263. _type = 'application/json'
  264. }
  265. uni.request({
  266. url: _url,
  267. data: isGet || isQuery ? '' : obj.params || '',
  268. header: {
  269. 'content-type': _type,
  270. 'x-token': store.getters.token
  271. },
  272. method: obj.method ? obj.method : 'POST',
  273. success: function (ress) {
  274. if (obj.isLoading) {
  275. uni.hideLoading()
  276. }
  277. const res = replaceStringInObject(
  278. ress.data,
  279. ['https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/', 'https://zfire-jsm-h.oss-cn-shenzhen.aliyuncs.com/'],
  280. process.env.VUE_APP_BASE_URL + process.env.VUE_APP_BASE_API + '/common/img/get?key='
  281. )
  282. if (whiteCodes.indexOf(res.code) < 0) {
  283. if (res.code === 1001) {
  284. webLogin(true)
  285. reject(new Error(res.message || 'Error'))
  286. return {}
  287. }
  288. if (res.code === 4444) {
  289. // #ifdef H5
  290. uni.removeStorageSync(`APPID${getQueryVariable('appid')}_token`)
  291. // #endif
  292. webLogin(true)
  293. reject(new Error(res.message || 'Error'))
  294. return {}
  295. }
  296. if (res.message || res.code) {
  297. uni.showToast({
  298. title: res.message || 'Error',
  299. icon: 'none',
  300. duration: 1500
  301. })
  302. }
  303. reject(new Error(res.message || 'Error'))
  304. } else {
  305. resolve(res)
  306. }
  307. },
  308. fail: function (err) {
  309. uni.hideLoading()
  310. uni.showModal({
  311. title: '提示',
  312. content: '网络连接失败' + JSON.stringify(err)
  313. })
  314. reject(err)
  315. }
  316. })
  317. })
  318. }
  319. export default {
  320. postJson,
  321. get,
  322. post,
  323. put,
  324. del
  325. }