request.js 10 KB

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