request.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // 基础配置
  2. import { showLoading, hideLoading } from '@/hooks/useLoading'
  3. import config1 from "@/config";
  4. import ls from "@/utils/store2";
  5. const baseUrl = config1.Host85;
  6. const timeout = 60000;
  7. // 不加loading
  8. const urlLoading = ['/list', '/page', '/field/params', '/dropdown', '/single', '/detail']
  9. import { CLIENT, lang, userToken, shopToken } from "@/composables/config";
  10. const LOGIN_PAGE_PATH = "/pages/login/index";
  11. // import useGlobalStore from "@/stores/use-global-store";
  12. import useUserStore from "@/stores/use-user-store";
  13. // const globalStore = useGlobalStore()
  14. export const getCurrentPageUrl = () => {
  15. const pages = getCurrentPages(); // UniApp获取当前页面栈
  16. const currentPage = pages[pages.length - 1];
  17. return currentPage.route; // 返回当前页面路径(如:pages/login/index)
  18. };
  19. // 请求拦截器
  20. const requestInterceptor = (config) => {
  21. if (!config.header) {
  22. config.header = {};
  23. }
  24. switch (config.type) {
  25. case 'HostShop':
  26. if (shopToken.value) {
  27. config.header["Access-Token"] = `${shopToken.value}`;
  28. }
  29. break;
  30. default:
  31. if (userToken.value) {
  32. config.header["Access-Token"] = `${userToken.value}`;
  33. }
  34. break;
  35. }
  36. if (lang.value) {
  37. config.header.Language = `${lang.value}`;
  38. }
  39. if (CLIENT.value) {
  40. config.header.CLIENT = `${CLIENT.value}`;
  41. }
  42. const userStore = useUserStore();
  43. const cId = userStore.userInfo?.cId;
  44. const method = String(config.method || "GET").toUpperCase();
  45. if (method === "GET") {
  46. config.data = { ...(config.data || {}) };
  47. } else {
  48. config.data = { ...(config.data || {}) };
  49. }
  50. if (!config.header["Content-Type"]) {
  51. config.header["Content-Type"] = "application/json";
  52. }
  53. return config;
  54. };
  55. // 记录是否正在跳转登录页
  56. let isRedirectingToLogin = false;
  57. // 响应拦截器
  58. const responseInterceptor = (response, options = {}) => {
  59. const { data, statusCode } = response;
  60. // 处理业务错误
  61. if (statusCode === 200) {
  62. if (options.responseType === "arraybuffer" || data instanceof ArrayBuffer) {
  63. return data;
  64. }
  65. // 1. 捕获 401 未授权错误
  66. if (data.code === 401 || data.code === 600) {
  67. // 关键:判断当前页面是否为登录页,避免循环跳转
  68. const currentPage = getCurrentPageUrl();
  69. if (currentPage === LOGIN_PAGE_PATH) {
  70. return Promise.reject({
  71. ...data,
  72. msg: data.message || "登录失败,请重试",
  73. });
  74. }
  75. userToken.value = "";
  76. // 3. 判断是否需要跳转登录(支持单个请求忽略跳转)
  77. const ignore401 = options.ignore401 || false; // 单个请求的配置
  78. if (ignore401) {
  79. return Promise.reject({
  80. ...data,
  81. code: 401,
  82. });
  83. }
  84. // 4. 提示并跳转登录页(防抖/防重复跳转处理)
  85. if (!isRedirectingToLogin) {
  86. isRedirectingToLogin = true;
  87. uni.showToast({
  88. title: "登录已过期,请重新登录",
  89. icon: "none",
  90. });
  91. setTimeout(() => {
  92. uni.reLaunch({
  93. url: LOGIN_PAGE_PATH,
  94. success: () => {
  95. uni.setStorageSync('logoutToSystem',1)
  96. ls.set('mode', 'customer');
  97. // globalStore.setMode('customer');
  98. isRedirectingToLogin = false;
  99. },
  100. fail: () => {
  101. isRedirectingToLogin = false;
  102. }
  103. });
  104. }, 1500);
  105. }
  106. return Promise.reject({
  107. ...data,
  108. code: 401,
  109. message: "登录已过期,请重新登录",
  110. });
  111. }
  112. if (data.code === 200) {
  113. return data;
  114. } else if (data.code === 400) {
  115. return Promise.reject(data);
  116. } else {
  117. uni.showToast({
  118. title: data.msg || "请求失败",
  119. icon: "none",
  120. });
  121. return Promise.reject(data);
  122. }
  123. } else {
  124. uni.showToast({
  125. title: `网络错误: ${statusCode}`,
  126. icon: "none",
  127. });
  128. return Promise.reject(response);
  129. }
  130. };
  131. // 错误处理
  132. const errorHandler = (error) => {
  133. uni.hideLoading();
  134. uni.showToast({
  135. title: "网络异常,请稍后重试",
  136. icon: "none",
  137. });
  138. return Promise.reject(error);
  139. };
  140. // 核心请求函数
  141. export const request = (options) => {
  142. // const host = config1[options.type || 'Host85'] || '';
  143. const host = config1[options.type || 'Host80'] || '';
  144. // 合并配置
  145. const config = {
  146. ...options,
  147. url: `${host}${options.url}`,
  148. method: options.method || "GET",
  149. timeout,
  150. };
  151. // 应用请求拦截器
  152. const processedConfig = requestInterceptor(config);
  153. return new Promise((resolve, reject) => {
  154. const needLoading = urlLoading.some(item => config.url.includes(item));
  155. if (!needLoading) {
  156. // showLoading();
  157. }
  158. uni.request({
  159. ...processedConfig,
  160. success: (response) => {
  161. try {
  162. const result = responseInterceptor(response, options);
  163. resolve(result);
  164. } catch (err) {
  165. reject(err);
  166. } finally {
  167. if (!needLoading) {
  168. // hideLoading();
  169. }
  170. }
  171. },
  172. fail: (error) => {
  173. const handledError = errorHandler(error);
  174. reject(handledError);
  175. if (!needLoading) {
  176. // hideLoading();
  177. }
  178. },
  179. });
  180. });
  181. };
  182. // ---------------------- 图片上传封装(新增)----------------------
  183. /**
  184. * 图片上传函数
  185. * @param {Object} options - 上传配置
  186. * @param {string} options.url - 上传接口路径(如 /Upload/Image)
  187. * @param {string|string[]} options.filePath - 图片临时路径(单文件:字符串;多文件:数组)
  188. * @param {string} [options.name=file] - 后端接收文件的字段名(默认file,需与后端一致)
  189. * @param {Object} [options.formData={}] - 额外表单参数(如业务ID、类型)
  190. * @param {Function} [options.onProgressUpdate] - 进度监听函数(可选)
  191. * @returns {Promise} - 上传结果
  192. */
  193. export const upload = (options) => {
  194. // 1. 处理基础配置
  195. const uploadConfig = {
  196. ...options,
  197. url: `${baseUrl}${options.url}`, // 完整上传接口地址
  198. timeout,
  199. name: options.name || "file", // 后端接收文件的字段名(默认file)
  200. filePath: options.filePath, // 图片临时路径
  201. formData: options.formData || {}, // 额外表单参数
  202. onProgressUpdate: options.onProgressUpdate, // 进度监听(可选)
  203. };
  204. // 2. 应用请求拦截器(添加token等header)
  205. const processedConfig = requestInterceptor(uploadConfig);
  206. // 3. 区分单文件/多文件上传
  207. return new Promise((resolve, reject) => {
  208. // 多文件上传(filePath为数组)
  209. if (Array.isArray(processedConfig.filePath)) {
  210. // 批量调用uni.uploadFile,并行上传
  211. const uploadPromises = processedConfig.filePath.map((filePath) => {
  212. return new Promise((innerResolve, innerReject) => {
  213. uni.uploadFile({
  214. ...processedConfig,
  215. filePath, // 单个文件路径
  216. success: (res) => {
  217. // 注意:uni.uploadFile的res.data是字符串,需转为JSON
  218. res.data = JSON.parse(res.data || "{}");
  219. try {
  220. const result = responseInterceptor(res);
  221. innerResolve(result);
  222. } catch (err) {
  223. innerReject(err);
  224. }
  225. },
  226. fail: (err) => innerReject(errorHandler(err)),
  227. });
  228. });
  229. });
  230. // 所有文件上传完成后 resolve
  231. Promise.all(uploadPromises).then(resolve).catch(reject);
  232. }
  233. // 单文件上传(filePath为字符串)
  234. else {
  235. uni.uploadFile({
  236. ...processedConfig,
  237. success: (res) => {
  238. res.data = JSON.parse(res.data || "{}"); // 转为JSON
  239. try {
  240. const result = responseInterceptor(res);
  241. resolve(result);
  242. } catch (err) {
  243. reject(err);
  244. }
  245. },
  246. fail: (err) => reject(errorHandler(err)),
  247. });
  248. }
  249. });
  250. };
  251. /**
  252. * 兼容性上传函数(按需直接调用)
  253. * @param {string} url - 接口相对路径,如 `/wasabi/api/upload/file`
  254. * @param {string|Object|File} file - 文件路径(临时路径字符串)或包含 path/url/tempFilePath 的对象或 File
  255. * @param {Object} [data] - 额外表单字段
  256. * @param {Object} [header] - 额外请求头
  257. * @param {boolean} [checkCode=true] - 是否走响应码检查(默认走)
  258. */
  259. export const uploadFile = (url, file, data = {}, header = {}, checkCode = true) => {
  260. return new Promise((resolve, reject) => {
  261. try {
  262. // 提取文件路径
  263. let filePath = file;
  264. if (file && typeof file === "object") {
  265. filePath = file.path || file.url || file.tempFilePath || file.filePath || file;
  266. }
  267. const finalUrl = `${baseUrl}${url}`;
  268. // 构建 headers,优先使用传入 header
  269. const headers = {
  270. ...(header || {}),
  271. };
  272. if (userToken.value) headers["Access-Token"] = `${userToken.value}`;
  273. if (lang.value) headers["Language"] = `${lang.value}`;
  274. if (CLIENT.value) headers["CLIENT"] = `${CLIENT.value}`;
  275. uni.uploadFile({
  276. url: finalUrl,
  277. filePath: filePath,
  278. name: "file",
  279. header: headers,
  280. formData: data || {},
  281. success: (res) => {
  282. try {
  283. // uni.uploadFile 的 res.data 是字符串
  284. res.data = JSON.parse(res.data || "{}");
  285. } catch (e) {
  286. res.data = {};
  287. }
  288. // 适配 responseInterceptor 接口
  289. const resp = { data: res.data, statusCode: res.statusCode };
  290. if (checkCode) {
  291. try {
  292. const result = responseInterceptor(resp);
  293. resolve(result);
  294. } catch (err) {
  295. reject(err);
  296. }
  297. } else {
  298. resolve(resp.data);
  299. }
  300. },
  301. fail: (err) => {
  302. reject(errorHandler(err));
  303. },
  304. });
  305. } catch (err) {
  306. reject(err);
  307. }
  308. });
  309. };
  310. // 快捷方法
  311. export const get = (url, data = {}, typeOrOptions = {}, options = {}) => {
  312. const mergedOptions =
  313. typeof typeOrOptions === "string"
  314. ? { type: typeOrOptions, ...(options || {}) }
  315. : (typeOrOptions || {});
  316. return request({
  317. url,
  318. method: "GET",
  319. data,
  320. ...mergedOptions,
  321. });
  322. };
  323. export const post = (url, data = {}, type, options = {}) => {
  324. return request({
  325. url,
  326. method: "POST",
  327. data,
  328. type,
  329. ...options,
  330. });
  331. };