| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { baseUrl, appid } from "../config";
- const App = getApp();
- function getHeader() {
- if (wx.getStorageSync("accessToken")) {
- return {
- "content-type": "application/json",
- "X-Mp-App-Id": appid,
- // "X-Store-Id": "",
- "Accept-Language": "zh-CN",
- "Accept": "application/json",
- "Authorization": "Bearer " + wx.getStorageSync("accessToken"),
- };
- }
- return {
- "content-type": "application/json",
- };
- }
- function showErrToast(e) {
- wx.showToast({
- title: typeof e === "string" ? e : e.errMsg || e.toString(),
- icon: "none",
- duration: 1500,
- });
- }
- function getPromise(url, data, method) {
- return new Promise((resolve, reject) => {
- const accessToken = wx.getStorageSync("accessToken");
- if (!accessToken) {
- // Cache the current API call
- const cachedCall = () => {
- wx.request({
- url: `${baseUrl}${url}`,
- header: getHeader(),
- method: method,
- data: data,
- success: function (res) {
- if (res.data.code === 200) {
- resolve(res.data.data);
- } else {
- if (res.statusCode === 401) {
- reject(401);
- } else {
- reject(res.data.message);
- }
- }
- },
- fail: function (err) {
- reject(err);
- },
- });
- };
- // Call App.getMUser to fetch accessToken
- App.getMUser()
- .then(() => {
- // Retry the cached API call after getting the token
- cachedCall();
- })
- .catch((err) => {
- console.error("Failed to fetch accessToken", err);
- showErrToast("Failed to fetch accessToken");
- reject(err);
- });
- } else {
- // Proceed with the API call if accessToken exists
- wx.request({
- url: `${baseUrl}${url}`,
- header: getHeader(),
- method: method,
- data: data,
- success: function (res) {
- if (res.statusCode === 200) {
- resolve(res.data);
- } else {
- if (res.statusCode === 401) {
- reject(401);
- } else {
- reject(res.data.message);
- }
- }
- },
- fail: function (err) {
- reject(err);
- },
- });
- }
- }).catch((e) => {
- console.error(`in promise error, url: ${baseUrl}${url}`);
- console.error(e);
- if (e) {
- showErrToast(e);
- }
- });
- }
- const http = {
- get: function (url, data) {
- return getPromise(url, data, "GET");
- },
- post: function (url, data) {
- return getPromise(url, data, "POST");
- },
- };
- export default http;
|