http.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. var config = require("config.js");
  2. //统一的网络请求方法
  3. function request(params, isGetTonken) {
  4. // 全局变量
  5. var globalData = getApp().globalData;
  6. // 如果正在进行登陆,就将非登陆请求放在队列中等待登陆完毕后进行调用
  7. if (!isGetTonken && globalData.isLanding) {
  8. globalData.requestQueue.push(params);
  9. console.log('ceshi');
  10. return;
  11. }
  12. wx.request({
  13. url: config.domain + params.url, //接口请求地址
  14. data: params.data,
  15. timeout:10000,
  16. header: {
  17. // 'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
  18. 'Authorization': params.login ? undefined : wx.getStorageSync('token') || wx.getStorageSync('tempToken')
  19. },
  20. method: params.method == undefined ? "POST" : params.method,
  21. dataType: 'json',
  22. responseType: params.responseType == undefined ? 'text' : params.responseType,
  23. success: function (res) {
  24. console.log(`接口地址${config.domain + params.url}:成功返回`,res);
  25. if (res.statusCode == 200) {
  26. //如果有定义了params.callBack,则调用 params.callBack(res.data)
  27. if (params.callBack) {
  28. params.callBack(res.data);
  29. }
  30. } else if (res.statusCode == 500) {
  31. wx.hideLoading()
  32. setTimeout(() => {
  33. wx.showToast({
  34. title: res.data || res.data.message,
  35. icon: "none"
  36. })
  37. }, 1)
  38. } else if (res.statusCode == 401) {
  39. if (!params.dontTrunLogin) {
  40. if (!wx.getStorageSync('token')) {
  41. // 添加到请求队列
  42. globalData.requestQueue.push(params);
  43. // 是否正在登陆
  44. if (!globalData.isLanding) {
  45. globalData.isLanding = true
  46. //重新获取token,再次请求接口
  47. getToken();
  48. }
  49. } else {
  50. wx.removeStorageSync('token')
  51. wx.removeStorageSync('loginResult')
  52. wx.hideLoading();
  53. wx.showModal({
  54. title: '提示',
  55. content: '登录已过期,请重新登录~',
  56. showCancel: false,
  57. success: modalRes => {
  58. if (modalRes.confirm) {
  59. wx.redirectTo({
  60. url: '/pages/login/login',
  61. })
  62. }
  63. }
  64. })
  65. }
  66. }
  67. } else if (res.statusCode == 400 && params.errCallBack) {
  68. if (params.errCallBack) {
  69. params.errCallBack(res);
  70. }
  71. if (!globalData.isLanding) {
  72. wx.hideLoading();
  73. }
  74. } else if (res.statusCode == 400 && !params.errCallBack) {
  75. wx.hideLoading()
  76. setTimeout(() => {
  77. wx.showToast({
  78. title: res.data,
  79. icon: "none"
  80. })
  81. }, 1)
  82. } else {
  83. //如果有定义了params.errCallBack,则调用 params.errCallBack(res.data)
  84. if (params.errCallBack) {
  85. params.errCallBack(res);
  86. }
  87. if (!globalData.isLanding) {
  88. wx.hideLoading();
  89. }
  90. }
  91. },
  92. fail: function (err) {
  93. console.warn(`接口地址${config.domain + params.url}:报错返回`,res);
  94. wx.hideLoading();
  95. setTimeout(() => {
  96. wx.showToast({
  97. title: err.message || "服务器出了点小差",
  98. icon: "none"
  99. });
  100. }, 1)
  101. },
  102. complete: function (res) {
  103. console.log(`接口地址${config.domain + params.url}:完成`,res,params.data);
  104. }
  105. })
  106. }
  107. //上传文件统一接口
  108. function upload(params) {
  109. wx.uploadFile({
  110. url: config.domain + params.url,
  111. filePath: params.filePath,
  112. name: params.name,
  113. header: {
  114. 'Content-Type': 'multipart/form-data',
  115. 'Authorization': params.login ? undefined : wx.getStorageSync('token')
  116. },
  117. dataType: 'json',
  118. responseType: params.responseType == undefined ? 'json' : params.responseType,
  119. success: function (res) {
  120. console.log(res);
  121. //console.log(res);
  122. if (res.statusCode == 200) {
  123. //如果有定义了params.callBack,则调用 params.callBack(res.data)
  124. if (params.callBack) {
  125. params.callBack(res.data);
  126. }
  127. } else {
  128. wx.showToast({
  129. title: res.message || "服务器出了点小差",
  130. icon: "none"
  131. });
  132. }
  133. },
  134. fail: function (err) {
  135. wx.hideLoading();
  136. }
  137. })
  138. }
  139. //通过code获取token,并保存到缓存
  140. var getToken = function (fn) {
  141. wx.login({
  142. success: res => {
  143. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  144. console.log(res);
  145. request({
  146. login: true,
  147. url: '/appLogin',
  148. data: {
  149. principal: res.code,
  150. appType: 1
  151. },
  152. callBack: result => {
  153. loginSuccess(result, fn)
  154. }
  155. }, true)
  156. }
  157. })
  158. }
  159. function loginSuccess(result, fn) {
  160. // 保存登陆信息
  161. wx.setStorageSync('loginResult', result)
  162. // 没有获取到用户昵称,说明服务器没有保存用户的昵称,也就是用户授权的信息并没有传到服务器
  163. if (!result.pic) {
  164. updateUserInfo();
  165. }
  166. if (!result.enabled) {
  167. wx.showModal({
  168. showCancel: false,
  169. title: '提示',
  170. content: '您已被禁用,不能购买,请联系客服'
  171. })
  172. wx.setStorageSync('token', '');
  173. } else {
  174. wx.setStorageSync('token', 'bearer' + result.access_token); //把token存入缓存,请求接口数据时要用
  175. }
  176. var globalData = getApp().globalData;
  177. globalData.isLanding = false;
  178. while (globalData.requestQueue.length) {
  179. request(globalData.requestQueue.pop());
  180. }
  181. if (fn) {
  182. fn()
  183. }
  184. }
  185. // 更新用户头像昵称
  186. function updateUserInfo() {
  187. wx.getUserInfo({
  188. success: (res) => {
  189. var userInfo = JSON.parse(res.rawData)
  190. request({
  191. url: "/p/user/setUserInfo",
  192. method: "PUT",
  193. data: {
  194. avatarUrl: userInfo.avatarUrl,
  195. nickName: userInfo.nickName
  196. }
  197. });
  198. }
  199. })
  200. }
  201. //获取购物车商品数量
  202. function getCartCount() {
  203. var params = {
  204. url: "/p/shopCart/prodCount",
  205. method: "GET",
  206. dontTrunLogin: true,
  207. data: {},
  208. callBack: function (res) {
  209. if (res > 0) {
  210. wx.setTabBarBadge({
  211. index: 1,
  212. text: res + "",
  213. })
  214. var app = getApp();
  215. app.globalData.totalCartCount = res;
  216. } else {
  217. wx.removeTabBarBadge({
  218. index: 2
  219. })
  220. var app = getApp();
  221. app.globalData.totalCartCount = 0;
  222. }
  223. }
  224. };
  225. request(params);
  226. }
  227. // 查看是否授权
  228. function isUserAuthInfo() {
  229. // 查看是否授权
  230. wx.getSetting({
  231. success(res) {
  232. if (res.authSetting['scope.userInfo']) {
  233. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  234. wx.getUserInfo({
  235. success: function (res) {
  236. console.log(res.userInfo)
  237. }
  238. })
  239. }
  240. }
  241. })
  242. }
  243. exports.getToken = getToken;
  244. exports.request = request;
  245. exports.getCartCount = getCartCount;
  246. exports.updateUserInfo = updateUserInfo;
  247. exports.upload = upload;
  248. exports.loginSuccess = loginSuccess;