request.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. const common_vendor = require("../common/vendor.js");
  3. const BASE_URL = "https://api.example.com";
  4. const TIMEOUT = 1e4;
  5. const request = (options) => {
  6. return new Promise((resolve, reject) => {
  7. const token = common_vendor.index.getStorageSync("token") || "";
  8. common_vendor.index.request({
  9. url: BASE_URL + options.url,
  10. method: options.method || "GET",
  11. data: options.data || {},
  12. header: {
  13. "Content-Type": "application/json",
  14. "Authorization": token ? `Bearer ${token}` : ""
  15. },
  16. timeout: TIMEOUT,
  17. success: (res) => {
  18. const { statusCode, data } = res;
  19. if (statusCode === 200) {
  20. if (data.code === 0 || data.code === 200 || data.success) {
  21. resolve(data);
  22. } else {
  23. common_vendor.index.showToast({
  24. title: data.message || data.msg || "请求失败",
  25. icon: "none",
  26. duration: 2e3
  27. });
  28. reject(data);
  29. }
  30. } else if (statusCode === 401) {
  31. common_vendor.index.removeStorageSync("userInfo");
  32. common_vendor.index.removeStorageSync("token");
  33. common_vendor.index.reLaunch({
  34. url: "/pages/login/login"
  35. });
  36. reject({ message: "未授权,请重新登录" });
  37. } else {
  38. common_vendor.index.showToast({
  39. title: "网络请求失败",
  40. icon: "none",
  41. duration: 2e3
  42. });
  43. reject(res);
  44. }
  45. },
  46. fail: (err) => {
  47. common_vendor.index.showToast({
  48. title: "网络连接失败",
  49. icon: "none",
  50. duration: 2e3
  51. });
  52. reject(err);
  53. }
  54. });
  55. });
  56. };
  57. const post = (url, data) => {
  58. return request({ url, method: "POST", data });
  59. };
  60. exports.post = post;
  61. //# sourceMappingURL=../../.sourcemap/mp-weixin/api/request.js.map