http.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. wx.request({
  28. url: `${baseUrl}${url}`,
  29. header: getHeader(),
  30. method: method,
  31. data: data,
  32. success: function (res) {
  33. if (res.data.code === 200) {
  34. resolve(res.data.data);
  35. } else {
  36. if (res.statusCode === 401) {
  37. reject(401);
  38. } else {
  39. reject(res.data.message);
  40. }
  41. }
  42. },
  43. fail: function (err) {
  44. reject(err);
  45. },
  46. });
  47. }).catch((e) => {
  48. // if (401 === e) {
  49. // redirect to login page
  50. // wx.navigateTo({
  51. // url: "/pages/login/login",
  52. // });
  53. // } else {
  54. console.error(`in promise error, url: ${baseUrl}${url}`);
  55. console.error(e);
  56. if (e) {
  57. showErrToast(e);
  58. }
  59. // }
  60. });
  61. }
  62. const http = {
  63. get: function (url, data) {
  64. return getPromise(url, data, "GET");
  65. },
  66. post: function (url, data) {
  67. return getPromise(url, data, "POST");
  68. },
  69. };
  70. export default http;