request.js 10 KB

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