request.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 if (data.code === 400) {
  97. return Promise.reject(data);
  98. } else {
  99. uni.showToast({
  100. title: data.msg || "请求失败",
  101. icon: "none",
  102. });
  103. return Promise.reject(data);
  104. }
  105. } else {
  106. uni.showToast({
  107. title: `网络错误: ${statusCode}`,
  108. icon: "none",
  109. });
  110. return Promise.reject(response);
  111. }
  112. };
  113. // 错误处理
  114. const errorHandler = (error) => {
  115. uni.hideLoading();
  116. uni.showToast({
  117. title: "网络异常,请稍后重试",
  118. icon: "none",
  119. });
  120. return Promise.reject(error);
  121. };
  122. // 核心请求函数
  123. export const request = (options) => {
  124. // const host = config1[options.type || 'Host85'] || '';
  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. };