request.js 9.6 KB

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