request.js 11 KB

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