request.js 9.8 KB

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