http.js 1.7 KB

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