http.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { baseUrl, appid } from "../config";
  2. const App = getApp();
  3. function getHeader() {
  4. if (wx.getStorageSync("accessToken")) {
  5. return {
  6. "content-type": "application/json",
  7. "X-Mp-App-Id": appid,
  8. // "X-Store-Id": "",
  9. "Accept-Language": "zh-CN",
  10. "Accept": "application/json",
  11. "Authorization": "Bearer " + wx.getStorageSync("accessToken"),
  12. };
  13. }
  14. return {
  15. "content-type": "application/json",
  16. };
  17. }
  18. function showErrToast(e) {
  19. wx.showToast({
  20. title: typeof e === "string" ? e : e.errMsg || e.toString(),
  21. icon: "none",
  22. duration: 1500,
  23. });
  24. }
  25. function getPromise(url, data, method) {
  26. return new Promise((resolve, reject) => {
  27. const accessToken = wx.getStorageSync("accessToken");
  28. if (!accessToken) {
  29. // Cache the current API call
  30. const cachedCall = () => {
  31. wx.request({
  32. url: `${baseUrl}${url}`,
  33. header: getHeader(),
  34. method: method,
  35. data: data,
  36. success: function (res) {
  37. if (res.data.code === 200) {
  38. resolve(res.data.data);
  39. } else {
  40. if (res.statusCode === 401) {
  41. reject(401);
  42. } else {
  43. reject(res.data.message);
  44. }
  45. }
  46. },
  47. fail: function (err) {
  48. reject(err);
  49. },
  50. });
  51. };
  52. // Call App.getMUser to fetch accessToken
  53. App.getMUser()
  54. .then(() => {
  55. // Retry the cached API call after getting the token
  56. cachedCall();
  57. })
  58. .catch((err) => {
  59. console.error("Failed to fetch accessToken", err);
  60. showErrToast("Failed to fetch accessToken");
  61. reject(err);
  62. });
  63. } else {
  64. // Proceed with the API call if accessToken exists
  65. wx.request({
  66. url: `${baseUrl}${url}`,
  67. header: getHeader(),
  68. method: method,
  69. data: data,
  70. success: function (res) {
  71. if (res.data.code === 200) {
  72. resolve(res.data.data);
  73. } else {
  74. if (res.statusCode === 401) {
  75. reject(401);
  76. } else {
  77. reject(res.data.message);
  78. }
  79. }
  80. },
  81. fail: function (err) {
  82. reject(err);
  83. },
  84. });
  85. }
  86. }).catch((e) => {
  87. console.error(`in promise error, url: ${baseUrl}${url}`);
  88. console.error(e);
  89. if (e) {
  90. showErrToast(e);
  91. }
  92. });
  93. }
  94. const http = {
  95. get: function (url, data) {
  96. return getPromise(url, data, "GET");
  97. },
  98. post: function (url, data) {
  99. return getPromise(url, data, "POST");
  100. },
  101. };
  102. export default http;