http.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. const common_vendor = require("../common/vendor.js");
  3. const baseURL = "http://192.168.168.71:8080";
  4. const httpInterceptor = {
  5. // 拦截前触发
  6. invoke(options) {
  7. if (!options.url.startsWith("http")) {
  8. options.url = baseURL + options.url;
  9. }
  10. options.timeout = 3e4;
  11. options.header = {
  12. ...options.header,
  13. "source-client": "miniapp"
  14. };
  15. }
  16. };
  17. common_vendor.index.addInterceptor("request", httpInterceptor);
  18. const http = (options) => {
  19. return new Promise((resolve, reject) => {
  20. common_vendor.index.request({
  21. ...options,
  22. // 响应成功
  23. success(res) {
  24. if (res.statusCode >= 200 && res.statusCode < 300) {
  25. if (res.data.code == 401) {
  26. common_vendor.index.redirectTo({ url: "/" });
  27. } else {
  28. resolve(res.data);
  29. }
  30. } else if (res.statusCode === 401) {
  31. common_vendor.index.redirectTo({ url: "/" });
  32. reject(res);
  33. } else {
  34. common_vendor.index.showToast({
  35. icon: "none",
  36. title: res.data.msg || "请求错误"
  37. });
  38. reject(res);
  39. }
  40. },
  41. // 响应失败
  42. fail(err) {
  43. common_vendor.index.showToast({
  44. icon: "none",
  45. title: "网络错误,换个网络试试"
  46. });
  47. reject(err);
  48. }
  49. });
  50. });
  51. };
  52. exports.http = http;