request.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. confirmText: '确定',
  97. success: (res) => {
  98. if (res.confirm) {
  99. } else if (res.cancel) {
  100. uni.redirectTo({ url: '/pages/index/index' });
  101. }
  102. }
  103. });
  104. reject();
  105. break;
  106. default:
  107. if (hideErrorModal) return;
  108. uni.showModal({
  109. title: data.msg || '系统异常,请联系管理员',
  110. confirmText: '确定',
  111. success: (res) => {
  112. if (res.confirm) {
  113. } else if (res.cancel) {
  114. uni.redirectTo({ url: '/pages/index/index' });
  115. }
  116. }
  117. });
  118. reject();
  119. break;
  120. }
  121. },
  122. fail: async (err) => {
  123. uni.showToast({
  124. title: '网络不稳定,请稍后刷新重试',
  125. icon: 'none'
  126. });
  127. await nextTick();
  128. reject(err);
  129. },
  130. complete: () => {
  131. loading && hideLoading();
  132. }
  133. });
  134. });
  135. }
  136. get(options) {
  137. return this.#request({
  138. ...options,
  139. method: 'GET'
  140. });
  141. }
  142. post(options) {
  143. return this.#request({
  144. ...options,
  145. method: 'POST'
  146. });
  147. }
  148. put(options) {
  149. return this.#request({
  150. ...options,
  151. method: 'PUT'
  152. });
  153. }
  154. delete(options) {
  155. return this.#request({
  156. ...options,
  157. method: 'DELETE'
  158. });
  159. }
  160. }
  161. export const api = new Request();