request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import {
  2. HTTP_REQUEST_URL,
  3. HEADER,
  4. TOKENNAME,
  5. HEADERPARAMS,
  6. WHITELIST,
  7. } from "@/config/app";
  8. import { toLogin, checkLogin } from "@/libs/login";
  9. import { useAppStore } from "@/stores/app";
  10. import { useToast } from "@/hooks/useToast";
  11. /**
  12. * 发送请求
  13. */
  14. function baseRequest(
  15. url,
  16. method,
  17. data,
  18. { noAuth = false, noVerify = false },
  19. params
  20. ) {
  21. const appStore = useAppStore();
  22. const { Toast } = useToast();
  23. let Url = HTTP_REQUEST_URL,
  24. header = HEADER;
  25. const TOKEN = appStore.tokenComputed;
  26. if (params != undefined) {
  27. header = HEADERPARAMS;
  28. }
  29. if (!noAuth) {
  30. //登录过期自动登录
  31. const currentPath = getCurrentPagePath();
  32. if (!TOKEN && !checkLogin() && !WHITELIST.includes(currentPath)) {
  33. // 未登录时,先判断当前页面是否在白名单
  34. Toast({ title: "未登录,请前往登录" });
  35. toLogin();
  36. return Promise.reject({
  37. code: 401,
  38. message: "未登录",
  39. });
  40. }
  41. }
  42. if (TOKEN) header[TOKENNAME] = TOKEN;
  43. return new Promise((reslove, reject) => {
  44. Url = HTTP_REQUEST_URL || "http://api.front.hdq.xbdzz.cn";
  45. uni.request({
  46. url: Url + "/api/front/" + url,
  47. method: method || "GET",
  48. header: header,
  49. timeout: 30000,
  50. data: data || {},
  51. success: (res) => {
  52. if (noVerify) reslove(res.data, res);
  53. else if (res.data.code == 200) reslove(res.data, res);
  54. else if ([401].indexOf(res.data.code) !== -1) {
  55. // 401及相关状态码处理:判断当前页面是否在白名单
  56. const currentPath = getCurrentPagePath();
  57. if (!WHITELIST.includes(currentPath)) {
  58. toLogin();
  59. }
  60. reject(res.data);
  61. } else {
  62. Toast({ title: res.data.message || "系统错误" });
  63. reject(res.data.message || "系统错误");
  64. }
  65. },
  66. fail: (msg) => {
  67. Toast({ title: "请求失败" });
  68. reject("请求失败");
  69. },
  70. });
  71. });
  72. }
  73. // 获取当前页面路径(格式如:/pages/index/index)
  74. function getCurrentPagePath() {
  75. const pages = getCurrentPages();
  76. if (pages.length === 0) return "";
  77. const currentPage = pages[pages.length - 1];
  78. return `/${currentPage.route}`;
  79. }
  80. const request = {};
  81. ["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  82. (method) => {
  83. request[method] = (api, data, opt, params) =>
  84. baseRequest(api, method, data, opt || {}, params);
  85. }
  86. );
  87. export default request;