config.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * API 配置工具
  3. * 根据运行环境自动选择正确的 API 地址
  4. */
  5. // 生产环境配置
  6. const PROD_CONFIG = {
  7. web: 'https://book.rrbrr.com/api',
  8. android: 'https://book.rrbrr.com/api',
  9. ios: 'https://book.rrbrr.com/api',
  10. h5: 'https://book.rrbrr.com/api',
  11. };
  12. // 开发环境配置
  13. const DEV_CONFIG = {
  14. // 开发模式(PC浏览器)- 需加 /api 以匹配 Vite 代理
  15. web: '/api',
  16. // 安卓真机 - 使用真实域名测试
  17. android: 'https://book.rrbrr.com/api',
  18. // iOS 真机 - 使用真实域名测试
  19. ios: 'https://book.rrbrr.com/api',
  20. // H5 - 需加 /api 以匹配 Vite 代理
  21. h5: '/api',
  22. };
  23. // 判断运行环境
  24. function getPlatform(): 'web' | 'android' | 'ios' | 'h5' {
  25. // #ifdef H5
  26. return 'h5';
  27. // #endif
  28. // #ifdef APP-PLUS
  29. // @ts-ignore
  30. const systemInfo = uni.getSystemInfoSync();
  31. const platform = (systemInfo.platform || '').toLowerCase();
  32. if (platform === 'android') return 'android';
  33. if (platform === 'ios') return 'ios';
  34. return 'android';
  35. // #endif
  36. return 'web';
  37. }
  38. // 获取当前 API 地址
  39. export function getApiBaseUrl(): string {
  40. const platform = getPlatform();
  41. // 生产环境使用固定域名
  42. // #ifdef H5
  43. if (process.env.NODE_ENV === 'production') {
  44. return PROD_CONFIG.h5;
  45. }
  46. // #endif
  47. // #ifdef H5
  48. // H5 环境判断是否在微信小程序模拟器中运行
  49. // @ts-ignore
  50. if (typeof window !== 'undefined' && window.__uniConfig && window.__uniConfig.platform === 'mp-weixin') {
  51. return DEV_CONFIG.web;
  52. }
  53. return DEV_CONFIG.h5;
  54. // #endif
  55. // @ts-ignore
  56. return DEV_CONFIG[platform];
  57. }
  58. // 获取后端服务器地址(不含 /api)
  59. export function getServerBaseUrl(): string {
  60. const apiUrl = getApiBaseUrl();
  61. return apiUrl.replace('/api', '');
  62. }
  63. // 获取前端基础地址(用于生成分享链接)
  64. export function getBaseUrl(): string {
  65. // #ifdef H5
  66. if (typeof window !== 'undefined') {
  67. return window.location.origin;
  68. }
  69. // #endif
  70. const apiUrl = getApiBaseUrl();
  71. return apiUrl.replace('/api', '');
  72. }
  73. // 获取局域网 IP 地址
  74. export function getLocalIP(): string {
  75. // 可以通过执行系统命令获取,或者硬编码配置
  76. // 这里返回空字符串,用户需要在 DEV_CONFIG 中配置
  77. return '';
  78. }