request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. const common_vendor = require("../common/vendor.js");
  3. const BASE_URL = "http://127.0.0.1:8080";
  4. const CLIENT_ID = "e48ac397bff4f031b14d6e671eee49c3";
  5. let isRedirectingToLogin = false;
  6. function getToken() {
  7. return common_vendor.index.getStorageSync("token") || "";
  8. }
  9. function redirectToLogin() {
  10. if (isRedirectingToLogin)
  11. return;
  12. isRedirectingToLogin = true;
  13. common_vendor.index.showToast({ title: "登录已失效,请重新登录", icon: "none", duration: 1500 });
  14. setTimeout(() => {
  15. isRedirectingToLogin = false;
  16. common_vendor.index.reLaunch({ url: "/pages/login/index" });
  17. }, 1500);
  18. }
  19. function request(options = {}) {
  20. const { url, method = "GET", data = {}, params = {}, header = {} } = options;
  21. const token = getToken();
  22. const headers = {
  23. "Content-Type": "application/json",
  24. "clientid": CLIENT_ID,
  25. "Authorization": "Bearer " + token,
  26. ...header
  27. };
  28. let requestData = data;
  29. let requestUrl = BASE_URL + url;
  30. if (method.toUpperCase() === "GET") {
  31. const allParams = { ...params, ...data };
  32. const paramString = Object.keys(allParams).filter((key) => allParams[key] !== void 0 && allParams[key] !== null && allParams[key] !== "").map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(allParams[key])}`).join("&");
  33. if (paramString) {
  34. requestUrl += (requestUrl.includes("?") ? "&" : "?") + paramString;
  35. }
  36. requestData = {};
  37. }
  38. return new Promise((resolve, reject) => {
  39. common_vendor.index.request({
  40. url: requestUrl,
  41. method,
  42. data: requestData,
  43. header: headers,
  44. success(res) {
  45. const { code, msg, data: data2, total, rows } = res.data;
  46. if (code === 200) {
  47. const result = {};
  48. if (data2 !== void 0)
  49. result.data = data2;
  50. if (total !== void 0)
  51. result.total = total;
  52. if (rows !== void 0)
  53. result.rows = rows;
  54. resolve(result);
  55. } else if (code === 401) {
  56. redirectToLogin();
  57. reject(new Error("登录已失效"));
  58. } else if (code === 500) {
  59. reject(new Error(msg));
  60. } else {
  61. reject(new Error(msg || "请求失败"));
  62. }
  63. },
  64. fail(err) {
  65. const message = err.errMsg || "网络请求失败";
  66. common_vendor.index.showToast({ title: message, icon: "none" });
  67. reject(new Error(message));
  68. }
  69. });
  70. });
  71. }
  72. exports.request = request;
  73. //# sourceMappingURL=../../.sourcemap/mp-weixin/utils/request.js.map