guoyu/fronted_uniapp/yuyin/utils/config.js

137 lines
4.0 KiB
JavaScript
Raw Normal View History

2025-12-03 18:58:36 +08:00
import '../polyfills/url.js'
/**
* 应用配置
*
* 部署说明
* - 支持从本地存储读取服务器地址配置优先
* - 如果没有配置使用默认的生产服务器地址
* - 支持离线局域网使用在设置中配置局域网服务器IP即可
*
* 配置方法
* 1. 通过代码设置uni.setStorageSync('server_host', '192.168.1.100')
* 2. 通过设置界面配置需要实现设置页面
*/
// 默认服务器配置(仅在未配置本地存储时使用)
const resolveIsDev = () => {
// Node 构建环境变量例如process.env.NODE_ENV
if (typeof process !== 'undefined' && process.env) {
if (typeof process.env.NODE_ENV !== 'undefined') {
return process.env.NODE_ENV !== 'production'
}
}
// 兜底HBuilderX 运行模式下提供的 globalThis.__DEV__ 标记
if (typeof globalThis !== 'undefined' && typeof globalThis.__DEV__ !== 'undefined') {
return !!globalThis.__DEV__
}
return false
}
const IS_DEV = resolveIsDev()
const DEFAULT_SERVER_HOST = '192.168.0.106' // 服务器地址
const DEFAULT_SERVER_PORT = 8080 // 后端端口
const DEV_SERVER_HOST = '192.168.0.106' // 开发服务器地址
const DEV_SERVER_PORT = 8080
const isH5 = typeof window !== 'undefined' && typeof document !== 'undefined'
// 本地存储的key
const STORAGE_SERVER_HOST_KEY = 'server_host'
const STORAGE_SERVER_PORT_KEY = 'server_port'
/**
* 获取服务器地址配置优先从本地存储读取
*/
function getServerConfig() {
if (IS_DEV && isH5) {
return {
serverHost: DEV_SERVER_HOST,
serverPort: DEV_SERVER_PORT
}
}
let serverHost = null
let serverPort = DEFAULT_SERVER_PORT
try {
// 优先从本地存储读取配置
const storedHost = uni.getStorageSync(STORAGE_SERVER_HOST_KEY)
const storedPort = uni.getStorageSync(STORAGE_SERVER_PORT_KEY)
// 生产环境:使用存储的配置或默认生产环境配置
if (storedHost) {
serverHost = storedHost
}
if (storedPort) {
serverPort = parseInt(storedPort) || DEFAULT_SERVER_PORT
}
} catch (e) {
console.warn('读取服务器配置失败:', e)
}
// 如果没有配置,使用默认值
if (!serverHost) {
serverHost = DEFAULT_SERVER_HOST
}
// 生产环境:已配置生产服务器地址,无需特殊处理
return { serverHost, serverPort }
}
/**
* 设置服务器地址配置
* @param {String} host 服务器IP或域名
* @param {Number} port 服务器端口可选默认8080
*/
function setServerConfig(host, port = DEFAULT_SERVER_PORT) {
try {
uni.setStorageSync(STORAGE_SERVER_HOST_KEY, host)
uni.setStorageSync(STORAGE_SERVER_PORT_KEY, port)
return true
} catch (e) {
console.error('保存服务器配置失败:', e)
return false
}
}
// 获取服务器配置
const { serverHost, serverPort } = getServerConfig()
// API基础地址
let API_BASE_URL = `http://${serverHost}:${serverPort}`
// H5环境如果访问的是localhost/192.168.0.106,跟随当前主机
if (typeof window !== 'undefined' && window.location) {
const hostname = window.location.hostname
if (hostname === 'localhost' || hostname === '192.168.0.106') {
API_BASE_URL = `http://${hostname}:${serverPort}`
}
}
// 文件访问地址
let FILE_BASE_URL = API_BASE_URL
export default {
API_BASE_URL,
FILE_BASE_URL,
// Token存储key
TOKEN_KEY: 'token',
// 用户信息存储key
USER_INFO_KEY: 'userInfo',
// 请求超时时间(毫秒)
REQUEST_TIMEOUT: 30000,
// 服务器配置相关
getServerConfig,
setServerConfig,
// 获取当前服务器地址(用于显示)
getCurrentServerUrl: () => {
const { serverHost, serverPort } = getServerConfig()
return `http://${serverHost}:${serverPort}`
}
}