request.js 9.8 KB

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