request.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*
  2. * @Author: your name
  3. * @Date: 2021-06-23 22:29:23
  4. * @LastEditTime: 2021-06-24 23:54:06
  5. * @LastEditors: Please set LastEditors
  6. * @Description: In User Settings Edit
  7. * @FilePath: \Mina_B_T\miniprogram\utils\request.js
  8. */
  9. /**
  10. * 这边主要是为公共请求方法服务的 同时支持回调与promise.then两种获取值的方法
  11. * 我本人喜欢回调方法
  12. * 如果习惯promise的本方法依旧支持
  13. */
  14. import { dont_login } from "./config_api";
  15. import { no_openid } from "./config_api";
  16. import { getNetworkType, getDataType, getUrl, getUserId, login } from "./util";
  17. /*
  18. 请求方法
  19. @options 请求参数
  20. @status 是否携带userID
  21. */
  22. async function formatOption(options: any): Promise<any> {
  23. /**
  24. * 检测网络状况 并判断是否发起请求
  25. * 当无网络时传入 offline 并提示无网络
  26. */
  27. const networkType = await getNetworkType();
  28. if (networkType === 'offline') {
  29. wx.showToast({
  30. icon: 'none',
  31. title: '网络未连接',
  32. })
  33. options.success && options.success(networkType)
  34. return networkType
  35. }
  36. /* 拼接接口地址 */
  37. if (getDataType(options.url) !== 'String') {
  38. throw new TypeError('接口路径格式错误')
  39. }
  40. /*判断是否需要登陆才能调用api */
  41. options.dont_login = false; //默认全部需要登录
  42. if (dont_login.length && dont_login.includes(options.url)) {
  43. options.dont_login = true;
  44. }
  45. /**判断是否需要openid才能调用api */
  46. options.no_openid = false; //默认全部需要
  47. if (no_openid.length && no_openid.includes(options.url)) {
  48. options.no_openid = true;
  49. }
  50. /* 设置URL */
  51. options.url = await getUrl(options.url);
  52. /* 判断是否传入参数 */
  53. options.data = options.data ? options.data : {};
  54. /* 设置请求方式并转换为大写*/
  55. options.method = (options.type ? options.type : 'get').toUpperCase();
  56. /* 判断是否传入请求头 */
  57. options.header = options.header || {};
  58. /* 判断是否传入返回数据格式 */
  59. options.dataType = options.dataType || 'json';
  60. /* 判断是否传入响应数据格式 */
  61. options.responseType = options.responseType || 'text';
  62. /* 消除空值字段 */
  63. for (let key in options.data) {
  64. if (!options.data[key] && options.data[key] !== 0) {
  65. delete options.data[key]
  66. }
  67. }
  68. /* 根据dont_login判断是否需要登录 */
  69. if (options.dont_login) {
  70. return options;
  71. } else {
  72. /* 设置userID和usertoken */
  73. options.data = await getUserId(options.data);
  74. /** 当user_id与user_token不全时 提示登陆重新获取 */
  75. console.log('options=>', options);
  76. if (options.data.user_id && options.data.user_token) {
  77. return options;
  78. } else {
  79. login();
  80. return false
  81. }
  82. }
  83. }
  84. /**
  85. * @description: 实际执行的请求方法体 执行完之后既能执行回调也能返回promise对象调用
  86. * @param {any} opt 传入的参数对象
  87. * @return {*} 返回promise对象
  88. */
  89. export async function $request<T>(opt: any): Promise<responseOptions<T>> {
  90. let route = getCurrentPages();
  91. const options = await formatOption(opt)
  92. if (options === 'offline') return Promise.reject(options)
  93. if (!options) return Promise.reject(options);
  94. return new Promise((resolve, reject) => {
  95. wx.showLoading({
  96. mask: true,
  97. title: '加载中...',
  98. success: () => {
  99. console.log('loading start')
  100. }
  101. })
  102. wx.request({
  103. url: options.url,
  104. data: options.data,
  105. header: options.header,
  106. method: options.method,
  107. dataType: options.dataType,
  108. responseType: options.responseType,
  109. success: function (res) {
  110. wx.hideLoading({
  111. success: () => {
  112. console.log('loding end')
  113. }
  114. })
  115. // 判断是否含有成功方法并执行
  116. if (res.statusCode === 200) {
  117. const result: any = res.data
  118. console.log(result);
  119. result.errCode = result.errcode
  120. result.errMsg = result.errmsg
  121. const errCode = result.errcode || result.errCode;
  122. if (errCode === 0) {
  123. options.success && typeof options.success === 'function' && options.success(result);
  124. resolve(result);
  125. } else {
  126. // 判断是否含有失败方法并执行
  127. if (options.fail && typeof options.fail === 'function') {
  128. options.fail(result);
  129. reject(result);
  130. }
  131. if (errCode === 2008) {
  132. login(result.errMsg + ',请重新登录')
  133. return
  134. }
  135. if (errCode === 2009) {
  136. wx.showToast({
  137. title: result.errMsg || result.message,
  138. icon: 'none'
  139. })
  140. return
  141. }
  142. if (errCode === 2010) {
  143. login(result.errMsg)
  144. return
  145. }
  146. // model 判断是否自定义模态框或者提示框
  147. if (!options.model) {
  148. wx.showModal({
  149. title: '提示',
  150. content: result.errMsg || result.message || '网络异常,请检查后重试',
  151. showCancel: false
  152. })
  153. }
  154. }
  155. } else {
  156. options.success && typeof options.success === 'function' && options.success('offline')
  157. wx.showModal({
  158. title: '提示',
  159. content: '网络异常,请检查后重试',
  160. showCancel: false
  161. })
  162. }
  163. },
  164. fail: function (res) {
  165. // 判断是否含有失败方法并执行
  166. wx.hideLoading({
  167. success: () => {
  168. console.log('loading end')
  169. }
  170. })
  171. if (options.fail && typeof options.fail === 'function') {
  172. options.success && typeof options.success === 'function' && options.success('offline')
  173. options.fail(res);
  174. reject(res);
  175. wx.showModal({
  176. title: '提示',
  177. content: '网络异常,请检查后重试',
  178. showCancel: false
  179. })
  180. }
  181. },
  182. complete: (res: any) => {
  183. console.log('请求参数=>', options);
  184. console.log('请求结果=>', res.data.errmsg, res.data);
  185. console.log('服务器响应状态=>', res.statusCode);
  186. console.log('服务器响应结果=>', res);
  187. console.log('当前页面=>', route[route.length - 1].route);
  188. console.log(' ');
  189. wx.stopPullDownRefresh({
  190. success: () => {
  191. console.log(route[route.length - 1].route, '=> stopPullDownRefresh')
  192. }
  193. });
  194. // 判断是否含有complete方法并执行
  195. if (options.complete && typeof options.complete === 'function') {
  196. options.complete(res.data);
  197. resolve(res.data);
  198. }
  199. },
  200. })
  201. })
  202. }