http.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { baseUrl } from "../config";
  2. function getHeader() {
  3. if (wx.getStorageSync("token")) {
  4. return {
  5. "content-type": "application/json",
  6. "x-token": wx.getStorageSync("token"),
  7. };
  8. }
  9. return {
  10. "content-type": "application/json",
  11. };
  12. }
  13. function showErrToast(e) {
  14. wx.showToast({
  15. title: typeof e === "string" ? e : e.errMsg || e.toString(),
  16. icon: "none",
  17. duration: 1500,
  18. });
  19. }
  20. function getPromise(url, data, method) {
  21. return new Promise((resolve, reject) => {
  22. wx.request({
  23. url: `${baseUrl}${url}`,
  24. header: getHeader(),
  25. method: method,
  26. data: data,
  27. success: function (res) {
  28. if (res.data.code === 200) {
  29. resolve(res.data.data);
  30. } else {
  31. if (res.statusCode === 401) {
  32. reject(401);
  33. } else {
  34. reject(res.data.message);
  35. }
  36. }
  37. },
  38. fail: function (err) {
  39. reject(err);
  40. },
  41. });
  42. }).catch((e) => {
  43. if (401 === e) {
  44. // redirect to login page
  45. wx.navigateTo({
  46. url: "/pages/login/login",
  47. });
  48. } else {
  49. console.error(`in promise error, url: ${baseUrl}${url}`);
  50. console.error(e);
  51. if (e) {
  52. showErrToast(e);
  53. }
  54. }
  55. });
  56. }
  57. const http = {
  58. get: function (url, data) {
  59. return getPromise(url, data, "GET");
  60. },
  61. post: function (url, data) {
  62. return getPromise(url, data, "POST");
  63. },
  64. };
  65. export default http;