request.js 11 KB

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