request.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /**
  2. * 这边主要是为公共请求方法服务的 同时支持回调与promise.then两种获取值的方法
  3. * 我本人喜欢回调方法
  4. * 如果习惯promise的本方法依旧支持
  5. */
  6. const api = require('./api.js');
  7. const dont_login_api = require('./config_api.js').dont_login;
  8. const no_openid_api = require('./config_api.js').no_openid;
  9. import { Utils } from './util'
  10. import { Loading } from './loading'
  11. class Request {
  12. /**
  13. * @that {OBject} 挂载对象
  14. */
  15. constructor(that) {
  16. this._loading = new Loading();
  17. this.api = api;
  18. this._showModel = false;
  19. that.kx_request = this.$request.bind(this);
  20. that.kx_api = this.api;
  21. }
  22. /*
  23. 获取Openid
  24. @options {Object} request请求的参数
  25. @return 返回获取到的openID加入options并返回
  26. */
  27. getOpenid() {
  28. return new Promise((resolve, reject) => {
  29. const _openid = wx.getStorageSync('openid');
  30. if (_openid) {
  31. resolve(_openid);
  32. } else {
  33. wx.login({
  34. success: (res) => {
  35. const code = res.code;
  36. this.$request({
  37. // url:'',
  38. data: {
  39. code,
  40. },
  41. success: res => {
  42. wx.setStorage({
  43. key: 'openid',
  44. data: res.data.openid,
  45. success: res => {
  46. const openid = res.data.openid
  47. resolve(openid);
  48. }
  49. })
  50. }
  51. })
  52. }
  53. })
  54. }
  55. })
  56. }
  57. /*
  58. 请求方法
  59. @options 请求参数
  60. @status 是否携带userID
  61. */
  62. async $request(options) {
  63. /**
  64. * 检测网络状况 并判断是否发起请求
  65. * 当无网络时传入 offline 并提示无网络
  66. */
  67. const networkType = await Utils.getNetworkType();
  68. if (networkType === 'offline') {
  69. wx.showToast({
  70. icon: 'none',
  71. title: '网络未连接',
  72. })
  73. options.success && options.success(networkType)
  74. return Utils.getNetworkType()
  75. }
  76. /* 拼接接口地址 */
  77. if (Utils.getDataType(options.url) !== 'String') {
  78. throw new TypeError('接口路径格式错误')
  79. }
  80. /*判断是否需要登陆才能调用api */
  81. options.dont_login = false; //默认全部需要登录
  82. if (dont_login_api.length && dont_login_api.includes(options.url)) {
  83. options.dont_login = true;
  84. }
  85. /**判断是否需要openid才能调用api */
  86. options.no_openid = false; //默认全部需要
  87. if (no_openid_api.length && no_openid_api.includes(options.url)) {
  88. options.no_openid = true;
  89. }
  90. /* 设置URL */
  91. options.url = await Utils.getUrl(options.url);
  92. /* 判断是否传入参数 */
  93. options.data = options.data ? options.data : {};
  94. /* 设置请求方式并转换为大写*/
  95. options.method = (options.type ? options.type : 'get').toUpperCase();
  96. /* 判断是否传入请求头 */
  97. options.header = options.header || {};
  98. /* 判断是否传入返回数据格式 */
  99. options.dataType = options.dataType || 'json';
  100. /* 判断是否传入响应数据格式 */
  101. options.responseType = options.responseType || 'text';
  102. /* 消除空值字段 */
  103. for (let key in options.data) {
  104. if (!options.data[key] && options.data[key] !== 0) {
  105. delete options.data[key]
  106. }
  107. }
  108. /**根据判断写入openid */
  109. // if (!options.no_openid) {
  110. // options.data.openid = await this.getOpenid();
  111. // }
  112. /* 根据dont_login判断是否需要登录 */
  113. if (options.dont_login) {
  114. return this._request(options);
  115. } else {
  116. /* 设置userID和usertoken */
  117. let _options = await Utils.getUserId(options);
  118. /** 当user_id与user_token不全时 提示登陆重新获取 */
  119. if (_options.data.user_id && _options.data.user_token) {
  120. return this._request(_options);
  121. } else {
  122. this._doLogin();
  123. }
  124. }
  125. }
  126. /**
  127. * 实际执行的请求方法体
  128. * @opt 传入的参数对象
  129. * @return 返回promise对象
  130. * 执行完之后既能执行回调也能返回promise对象调用
  131. */
  132. _request(opt) {
  133. let route = getCurrentPages();
  134. const that = this;
  135. return new Promise((resolve, reject) => {
  136. that._loading.showLoading({
  137. mask: true,
  138. title: '加载中...',
  139. success: () => {
  140. console.log('loding start')
  141. }
  142. })
  143. wx.request({
  144. url: opt.url,
  145. data: opt.data,
  146. header: opt.header,
  147. method: opt.method,
  148. dataType: opt.dataType,
  149. responseType: opt.responseType,
  150. success: function (res) {
  151. that._loading.hideLoading({
  152. success: () => {
  153. console.log('loding end')
  154. }
  155. })
  156. // 判断是否含有成功方法并执行
  157. if (opt.success && typeof opt.success === 'function') {
  158. if (res.statusCode === 200) {
  159. const errcode = res.data.errcode;
  160. if (errcode === 0) {
  161. opt.success(res.data);
  162. resolve(res.data);
  163. } else {
  164. // 判断是否含有失败方法并执行
  165. if (opt.fail && typeof opt.fail === 'function') {
  166. opt.fail(res.data);
  167. reject(res.data);
  168. }
  169. if (errcode === 2008) {
  170. that._doLogin(res.data.errmsg + ',请重新登录')
  171. return
  172. }
  173. if (errcode === 2010) {
  174. that._doLogin(res.data.errmsg)
  175. return
  176. }
  177. // model 判断是否自定义模态框或者提示框
  178. if (!opt.model) {
  179. wx.showModal({
  180. title: '提示',
  181. content: res.data.errmsg || '网络异常,请检查后重试',
  182. showCancel: false
  183. })
  184. }
  185. }
  186. } else {
  187. opt.success && opt.success('offline')
  188. wx.showModal({
  189. title: '提示',
  190. content: '网络异常,请检查后重试',
  191. showCancel: false
  192. })
  193. }
  194. }
  195. },
  196. fail: function (res) {
  197. // 判断是否含有失败方法并执行
  198. that._loading.hideLoading({
  199. success: () => {
  200. console.log('loding end')
  201. }
  202. })
  203. if (opt.fail && typeof opt.fail === 'function') {
  204. opt.success && opt.success('offline')
  205. opt.fail(res.data);
  206. reject(res.data);
  207. wx.showModal({
  208. title: '提示',
  209. content: '网络异常,请检查后重试',
  210. showCancel: false
  211. })
  212. }
  213. },
  214. complete: (res) => {
  215. console.log('请求参数=>', opt);
  216. console.log('请求结果=>', res.data.errmsg, res.data);
  217. console.log('服务器响应状态=>', res.statusCode);
  218. console.log('服务器响应结果=>', res);
  219. console.log('当前页面=>', route[route.length - 1].route);
  220. console.log(' ');
  221. wx.stopPullDownRefresh({
  222. success: () => {
  223. console.log(route[route.length - 1].route, '=> stopPullDownRefresh')
  224. }
  225. });
  226. // 判断是否含有complete方法并执行
  227. if (opt.complete && typeof opt.complete === 'function') {
  228. opt.complete(res.data);
  229. resolve(res.data);
  230. }
  231. },
  232. })
  233. })
  234. }
  235. /**
  236. * 执行跳转登录页面操作
  237. */
  238. _doLogin(message = '你还未登录,请立即登录') {
  239. if (!this._showModel) {
  240. this._showModel = true;
  241. wx.showModal({
  242. title: '提示',
  243. content: message,
  244. cancelColor: '#888A8E',
  245. confirmColor: '#31364C',
  246. success: res => {
  247. if (res.confirm) {
  248. wx.navigateTo({
  249. url: '/pages/login/login',
  250. success: () => {
  251. this._showModel = false;
  252. }
  253. })
  254. }
  255. if (res.cancel) {
  256. this._showModel = false;
  257. }
  258. }
  259. })
  260. }
  261. }
  262. }
  263. module.exports = {
  264. Request: new Request(wx)
  265. }