request.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // 基础配置
  2. import { showLoading, hideLoading } from '@/hooks/useLoading'
  3. import config1 from "@/config";
  4. import ls from "@/utils/store2";
  5. import { whenDomainReady } from '@/utils/dynamicDomain';
  6. const SystemError = {
  7. "cn": "网络状态不佳,请稍后重试。",
  8. "en": "The network is not in good condition. Please try again later.",
  9. "vn": "Mạng không được tốt lắm. Vui lòng thử lại sau.",
  10. }
  11. const timeout = 60000;
  12. const sourceList = ['/chat/token/create','/custom/login']
  13. const getHost = (type = 'Host80') => config1[type] || config1.Host80;
  14. // 不加loading
  15. const urlLoading = ['/list', '/page', '/field/params', '/dropdown', '/single', '/detail']
  16. import { CLIENT, lang, userToken, shopToken } from "@/composables/config";
  17. const LOGIN_PAGE_PATH = "/pages/login/index";
  18. // import useGlobalStore from "@/stores/use-global-store";
  19. import useUserStore from "@/stores/use-user-store";
  20. // const globalStore = useGlobalStore()
  21. export const getCurrentPageUrl = () => {
  22. const pages = getCurrentPages(); // UniApp获取当前页面栈
  23. const currentPage = pages[pages.length - 1];
  24. return currentPage.route; // 返回当前页面路径(如:pages/login/index)
  25. };
  26. // 请求拦截器
  27. const requestInterceptor = (config) => {
  28. if (!config.header) {
  29. config.header = {};
  30. }
  31. switch (config.type) {
  32. case 'HostShop':
  33. if (shopToken.value) {
  34. config.header["Access-Token"] = `${shopToken.value}`;
  35. }
  36. break;
  37. default:
  38. if (userToken.value) {
  39. config.header["Access-Token"] = `${userToken.value}`;
  40. }
  41. break;
  42. }
  43. if (lang.value) {
  44. config.header.Language = `${lang.value}`;
  45. }
  46. if (CLIENT.value) {
  47. config.header.CLIENT = `${CLIENT.value}`;
  48. }
  49. config.header["X-System"] = config.header["X-System"] || 'B';
  50. // #ifdef APP-PLUS
  51. const hit = sourceList.some(item => config.url.includes(item))
  52. if (hit) {
  53. const { platform } = uni.getSystemInfoSync()
  54. const DEVICE_TYPE = {
  55. ios: 'PHONE_IOS',
  56. android: 'PHONE_ANDROID'
  57. }
  58. config.data.source = DEVICE_TYPE[platform] || ''
  59. }
  60. // #endif
  61. const userStore = useUserStore();
  62. const cId = userStore.userInfo?.cId;
  63. const method = String(config.method || "GET").toUpperCase();
  64. if (method === "GET") {
  65. config.data = { ...(config.data || {}) };
  66. } else {
  67. config.data = { ...(config.data || {}) };
  68. }
  69. if (!config.header["Content-Type"]) {
  70. config.header["Content-Type"] = "application/json";
  71. }
  72. return config;
  73. };
  74. // 记录是否正在跳转登录页
  75. let isRedirectingToLogin = false;
  76. // 响应拦截器
  77. const responseInterceptor = (response, options = {}) => {
  78. const { data, statusCode } = response;
  79. if (statusCode === 200) {
  80. if (options.responseType === "arraybuffer" || data instanceof ArrayBuffer) {
  81. return data;
  82. }
  83. if (data.code === 600) {
  84. const currentPage = getCurrentPageUrl();
  85. if (currentPage === LOGIN_PAGE_PATH) {
  86. return new Promise(() => { });
  87. }
  88. uni.$emit('logout');
  89. return new Promise(() => { });
  90. } else if (data.code === 500) {
  91. return {
  92. code: 500,
  93. msg: SystemError[lang.value] || SystemError['en']
  94. }
  95. } else if (data.code === 404) {
  96. return {
  97. code: 400,
  98. msg: SystemError[lang.value] || SystemError['en']
  99. }
  100. } else {
  101. return data
  102. }
  103. } else {
  104. return {
  105. code: 400,
  106. msg: SystemError[lang.value] || SystemError['en']
  107. }
  108. }
  109. };
  110. // 错误处理
  111. const errorHandler = (error) => {
  112. uni.hideLoading();
  113. uni.showToast({
  114. title: error.msg || SystemError[lang.value] || SystemError['en'],
  115. icon: "none",
  116. });
  117. return Promise.reject(error);
  118. };
  119. // 核心请求函数
  120. export const request = async (options) => {
  121. await whenDomainReady();
  122. const host = getHost(options.type || 'Host80');
  123. // 合并配置
  124. const config = {
  125. ...options,
  126. url: `${host}${options.url}`,
  127. method: options.method || "GET",
  128. timeout,
  129. };
  130. // 应用请求拦截器
  131. const processedConfig = requestInterceptor(config);
  132. return new Promise((resolve, reject) => {
  133. const needLoading = urlLoading.some(item => config.url.includes(item));
  134. console.log(needLoading,config.url)
  135. if (!needLoading) {
  136. // uni.showLoading({
  137. // mask:true
  138. // })
  139. // showLoading();
  140. }
  141. uni.request({
  142. ...processedConfig,
  143. success: (response) => {
  144. try {
  145. const result = responseInterceptor(response, options);
  146. resolve(result);
  147. } catch (err) {
  148. reject(err);
  149. } finally {
  150. if (!needLoading) {
  151. // uni.hideLoading()
  152. // hideLoading();
  153. }
  154. }
  155. },
  156. fail: (error) => {
  157. const handledError = errorHandler(error);
  158. reject(handledError);
  159. if (!needLoading) {
  160. // uni.hideLoading()
  161. // hideLoading();
  162. }
  163. },
  164. });
  165. });
  166. };
  167. // ---------------------- 图片上传封装(新增)----------------------
  168. /**
  169. * 图片上传函数
  170. * @param {Object} options - 上传配置
  171. * @param {string} options.url - 上传接口路径(如 /Upload/Image)
  172. * @param {string|string[]} options.filePath - 图片临时路径(单文件:字符串;多文件:数组)
  173. * @param {string} [options.name=file] - 后端接收文件的字段名(默认file,需与后端一致)
  174. * @param {Object} [options.formData={}] - 额外表单参数(如业务ID、类型)
  175. * @param {Function} [options.onProgressUpdate] - 进度监听函数(可选)
  176. * @returns {Promise} - 上传结果
  177. */
  178. export const upload = async (options) => {
  179. await whenDomainReady();
  180. // 1. 处理基础配置
  181. const uploadConfig = {
  182. ...options,
  183. url: `${getHost(options.type || 'Host85')}${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 = async (url, file, data = {}, header = {}, checkCode = true) => {
  246. await whenDomainReady();
  247. return new Promise((resolve, reject) => {
  248. try {
  249. // 提取文件路径
  250. let filePath = file;
  251. if (file && typeof file === "object") {
  252. filePath = file.path || file.url || file.tempFilePath || file.filePath || file;
  253. }
  254. const finalUrl = `${getHost('Host85')}${url}`;
  255. // 构建 headers,优先使用传入 header
  256. const headers = {
  257. ...(header || {}),
  258. };
  259. if (userToken.value) headers["Access-Token"] = `${userToken.value}`;
  260. if (lang.value) headers["Language"] = `${lang.value}`;
  261. if (CLIENT.value) headers["CLIENT"] = `${CLIENT.value}`;
  262. uni.uploadFile({
  263. url: finalUrl,
  264. filePath: filePath,
  265. name: "file",
  266. header: headers,
  267. formData: data || {},
  268. success: (res) => {
  269. try {
  270. // uni.uploadFile 的 res.data 是字符串
  271. res.data = JSON.parse(res.data || "{}");
  272. } catch (e) {
  273. res.data = {};
  274. }
  275. // 适配 responseInterceptor 接口
  276. const resp = { data: res.data, statusCode: res.statusCode };
  277. if (checkCode) {
  278. try {
  279. const result = responseInterceptor(resp);
  280. resolve(result);
  281. } catch (err) {
  282. reject(err);
  283. }
  284. } else {
  285. resolve(resp.data);
  286. }
  287. },
  288. fail: (err) => {
  289. reject(errorHandler(err));
  290. },
  291. });
  292. } catch (err) {
  293. reject(err);
  294. }
  295. });
  296. };
  297. // 快捷方法
  298. export const get = (url, data = {}, typeOrOptions = {}, options = {}) => {
  299. const mergedOptions =
  300. typeof typeOrOptions === "string"
  301. ? { type: typeOrOptions, ...(options || {}) }
  302. : (typeOrOptions || {});
  303. return request({
  304. url,
  305. method: "GET",
  306. data,
  307. ...mergedOptions,
  308. });
  309. };
  310. export const post = (url, data = {}, type, options = {}) => {
  311. return request({
  312. url,
  313. method: "POST",
  314. data,
  315. type,
  316. ...options,
  317. });
  318. };