request.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import Request from "@/lib/request/index.js";
  2. import { refreshTokenFn } from "@/api/login.js";
  3. import storage from "@/utils/storage.js";
  4. import { md5 } from "@/utils/md5.js";
  5. import Foundation from "@/utils/Foundation.js";
  6. import api from "@/config/api.js";
  7. import uuid from "@/utils/uuid.modified.js";
  8. /**
  9. * 无痛刷新token思路(如果不使用无痛刷新token,忽略此处注释)
  10. * 看了很多,有个问题一直得不到解决----‘多个接口请求,token失效,如何让获取token只获取一遍’、
  11. * 于是想到了闭包防抖......
  12. * 本方案并不是最佳方案,只是给你们提供一种思路。如果你有完美解决方案,可以分享一下
  13. */
  14. const expireToken = []; // 储存过期的token
  15. // 防抖闭包来一波
  16. function getTokenDebounce() {
  17. let lock = false;
  18. let success = false;
  19. return async function () {
  20. if (!lock) {
  21. lock = true;
  22. await refreshTokenFn(storage.getRefreshToken())
  23. .then((res) => {
  24. if (res.data.success) {
  25. let { accessToken, refreshToken } = res.data.result;
  26. storage.setAccessToken(accessToken);
  27. storage.setRefreshToken(refreshToken);
  28. success = true;
  29. lock = false;
  30. } else {
  31. cleanStorage();
  32. success = false;
  33. lock = false;
  34. }
  35. })
  36. .catch((error) => {
  37. cleanStorage();
  38. success = false;
  39. lock = false;
  40. });
  41. }
  42. return new Promise((resolve) => {
  43. // XXX 我只能想到通过轮询来看获取新的token是否结束,有好的方案可以说。一直看lock,直到请求失败或者成功
  44. const timer = setInterval(() => {
  45. if (!lock) {
  46. clearInterval(timer);
  47. if (success) {
  48. resolve("success");
  49. } else {
  50. cleanStorage();
  51. resolve("fail");
  52. }
  53. }
  54. }, 100); // 轮询时间可以自己看改成多少合适
  55. });
  56. };
  57. }
  58. function cleanStorage() {
  59. uni.showToast({
  60. title: "你的登录状态已过期,请重新登录",
  61. icon: "none",
  62. duration: 1500,
  63. });
  64. if (uni.showLoading()) {
  65. uni.hideLoading();
  66. }
  67. storage.setHasLogin(false);
  68. storage.setAccessToken("");
  69. storage.setRefreshToken("");
  70. console.log("清空token");
  71. storage.setUuid("");
  72. storage.setUserInfo({});
  73. uni.navigateTo({
  74. url: "/pages/passport/login",
  75. });
  76. }
  77. let http = new Request();
  78. const refreshToken = getTokenDebounce();
  79. http.setConfig((config) => {
  80. // 没有uuid创建
  81. if (!storage.getUuid()) {
  82. storage.setUuid(uuid.v1());
  83. }
  84. /* 设置全局配置 */
  85. config.baseURL = api.buyer;
  86. config.header = {
  87. ...config.header,
  88. };
  89. config.validateStatus = (statusCode) => {
  90. // 不论什么状态,统一在正确中处理
  91. return true;
  92. };
  93. return config;
  94. });
  95. http.interceptors.request.use(
  96. (config) => {
  97. /* 请求之前拦截器。可以使用async await 做异步操作 */
  98. let accessToken = storage.getAccessToken();
  99. if (accessToken) {
  100. const nonce = Foundation.randomString(6);
  101. const timestamp = parseInt(new Date().getTime() / 1000);
  102. const sign = md5(nonce + timestamp + accessToken);
  103. const _params = {
  104. nonce,
  105. timestamp,
  106. sign,
  107. };
  108. let params = config.params || {};
  109. params = { ...params, ..._params };
  110. config.params = params;
  111. config.header.accessToken = accessToken;
  112. /**
  113. * jwt 因为安卓以及ios没有window的属性
  114. * window.atob()这个函数 base64编码的使用方法就是btoa(),而用于解码的使用方法是atob(),
  115. * 所以使用手写 base-64 编码的字符串数据。
  116. */
  117. const atob = (str) => Buffer.from(str, "base64").toString("binary");
  118. // 判断如果过期时间小于我的当前时间,在请求上重新刷新token
  119. if (accessToken.split(".").length <= 1) {
  120. refresh();
  121. } else {
  122. if (
  123. JSON.parse(
  124. atob(
  125. accessToken.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")
  126. )
  127. ).exp < Math.round(new Date() / 1000)
  128. ) {
  129. refresh();
  130. }
  131. }
  132. }
  133. config.header = {
  134. ...config.header,
  135. uuid: storage.getUuid() || uuid.v1(),
  136. };
  137. console.log(config.header);
  138. return config;
  139. },
  140. (config) => {
  141. return Promise.reject(config);
  142. }
  143. );
  144. async function refresh() {
  145. // 本地储存的是过期token了,重新获取
  146. const getTokenResult = await refreshToken();
  147. if (getTokenResult === "success") {
  148. // 获取新的token成功 刷新当前页面
  149. let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  150. let curRoute = routes[routes.length - 1].route; //获取当前页面路由
  151. let curParam = routes[routes.length - 1].options; //获取路由参数
  152. // 拼接参数
  153. let param = "";
  154. for (let key in curParam) {
  155. param += "&" + key + "=" + curParam[key];
  156. }
  157. // 判断当前路径
  158. if (curRoute.indexOf("pages/tabbar") == 1) {
  159. uni.switchTab({
  160. url: "/" + curRoute + param.replace("&", "?"),
  161. });
  162. }
  163. uni.redirectTo({
  164. url: "/" + curRoute + param.replace("&", "?"),
  165. });
  166. }
  167. }
  168. // 必须使用异步函数,注意
  169. http.interceptors.response.use(
  170. async (response) => {
  171. /* 请求之后拦截器。可以使用async await 做异步操作 */
  172. // token存在并且token过期
  173. let token = storage.getAccessToken();
  174. if (
  175. (token && response.statusCode === 403) ||
  176. response.data.status === 403
  177. ) {
  178. // jwt token 过期了
  179. expireToken.push(token); // 把过期token 储存
  180. const currentToken = storage.getAccessToken();
  181. if (expireToken.includes(currentToken)) {
  182. refresh();
  183. }
  184. // 如果当前返回没登录
  185. } else if (
  186. (!token && response.statusCode === 403) ||
  187. response.data.code === 403
  188. ) {
  189. cleanStorage();
  190. // 如果当前状态码为正常但是success为不正常时
  191. } else if (
  192. (response.statusCode == 200 && !response.data.success) ||
  193. response.statusCode == 400
  194. ) {
  195. if (response.data.message) {
  196. uni.showToast({
  197. title: response.data.message,
  198. icon: "none",
  199. duration: 1500,
  200. });
  201. }
  202. }
  203. return response;
  204. },
  205. (error) => {
  206. return error;
  207. }
  208. );
  209. export { http };
  210. export const Method = {
  211. GET: "GET",
  212. POST: "POST",
  213. PUT: "PUT",
  214. DELETE: "DELETE",
  215. };