request.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import { useUserStore } from '@/store/user.js';
  2. import { nextTick } from 'vue';
  3. import { BASE_API_URL } from '@/settings/siteSetting.js';
  4. import { REDIRECT_KEY } from '@/settings/enums.js';
  5. let requestCount = 0,
  6. isShowingDialog = false;
  7. const showLoading = () => {
  8. if (requestCount === 0) {
  9. uni.showLoading({ mask: true });
  10. }
  11. requestCount++;
  12. };
  13. //隐藏loading
  14. const hideLoading = () => {
  15. requestCount--;
  16. if (requestCount <= 0) {
  17. uni.hideLoading();
  18. }
  19. };
  20. // 将对象转为 x-www-form-urlencoded 字符串(兼容小程序环境无 URLSearchParams)
  21. function toFormUrlEncoded(obj) {
  22. if (obj == null || typeof obj !== 'object') return '';
  23. return Object.keys(obj)
  24. .filter((k) => obj[k] != null && obj[k] !== '')
  25. .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]))
  26. .join('&');
  27. }
  28. // 获取当前页面路径以及参数
  29. export function getCurrentPageUrlWithArgs() {
  30. const pages = getCurrentPages();
  31. const currentPage = pages[pages.length - 1];
  32. const route = currentPage.route;
  33. const options = currentPage.options;
  34. let url = `/${route}?`;
  35. for (let key in options) {
  36. const value = options[key];
  37. url += `${key}=${value}&`;
  38. }
  39. url = url.substring(0, url.length - 1);
  40. return url;
  41. }
  42. export class Request {
  43. #request(config) {
  44. const userStore = useUserStore();
  45. let {
  46. headers = {
  47. 'Content-Type': 'application/json;charset=UTF-8',
  48. },
  49. url,
  50. method, // 请求类型
  51. loading = true, // 是否触发 loading
  52. timeout = 60 * 3000, // 请求超时时间
  53. returnResponse = false, // 是否返回原生数据
  54. message = true,
  55. hideErrorModal = false, // 报误弹窗
  56. params, // 请求参数
  57. formUrlEncoded = false, // 是否以 application/x-www-form-urlencoded 发送
  58. customizeUrl = '' //自定义url
  59. } = config;
  60. const header = {
  61. ...headers,
  62. Authorization: userStore.getToken
  63. };
  64. if (method.toUpperCase() === 'GET') {
  65. const now = Date.now();
  66. params = Object.assign(params || {}, { _t: now });
  67. }
  68. let data = params;
  69. if (formUrlEncoded && params && typeof params === 'object') {
  70. data = toFormUrlEncoded(params);
  71. header['Content-Type'] = 'application/x-www-form-urlencoded';
  72. }
  73. loading && showLoading();
  74. return new Promise((resolve, reject) => {
  75. uni.request({
  76. url: BASE_API_URL + url,
  77. header,
  78. method,
  79. timeout,
  80. data,
  81. dataType: 'json',
  82. success: async (res) => {
  83. const { data } = res;
  84. // 返回原生接口请求
  85. if (returnResponse) {
  86. resolve(res);
  87. return;
  88. }
  89. switch (data.code) {
  90. case 200:
  91. resolve(data.data);
  92. break;
  93. case 400:
  94. uni.showModal({
  95. title: data.msg || '系统异常,请联系管理员',
  96. cancelText: '回到首页',
  97. confirmText: '确定',
  98. success: (res) => {
  99. if (res.confirm) {
  100. } else if (res.cancel) {
  101. uni.redirectTo({ url: '/pages/index/index' });
  102. }
  103. }
  104. });
  105. reject();
  106. break;
  107. default:
  108. if (hideErrorModal) return;
  109. uni.showModal({
  110. title: data.msg || '系统异常,请联系管理员',
  111. cancelText: '回到首页',
  112. confirmText: '确定',
  113. success: (res) => {
  114. if (res.confirm) {
  115. } else if (res.cancel) {
  116. uni.redirectTo({ url: '/pages/index/index' });
  117. }
  118. }
  119. });
  120. reject();
  121. break;
  122. }
  123. },
  124. fail: async (err) => {
  125. uni.showToast({
  126. title: '网络不稳定,请稍后刷新重试',
  127. icon: 'none'
  128. });
  129. await nextTick();
  130. reject(err);
  131. },
  132. complete: () => {
  133. loading && hideLoading();
  134. }
  135. });
  136. });
  137. }
  138. get(options) {
  139. return this.#request({
  140. ...options,
  141. method: 'GET'
  142. });
  143. }
  144. post(options) {
  145. return this.#request({
  146. ...options,
  147. method: 'POST'
  148. });
  149. }
  150. put(options) {
  151. return this.#request({
  152. ...options,
  153. method: 'PUT'
  154. });
  155. }
  156. }
  157. export const api = new Request();