90 lines
2.5 KiB
JavaScript
90 lines
2.5 KiB
JavaScript
/**
|
||
* API 配置
|
||
* 统一管理后端接口地址,并根据环境自动切换
|
||
*/
|
||
|
||
import envConfig from '@/common/env.js'
|
||
|
||
const API_TARGETS = {
|
||
local: 'http://localhost:8091/',
|
||
prod: 'https://api.huayang-star.com/'
|
||
}
|
||
|
||
const ENV_ALIAS = {
|
||
development: 'local',
|
||
production: 'prod',
|
||
local: 'local',
|
||
prod: 'prod'
|
||
}
|
||
|
||
function normalizeBaseUrl(url) {
|
||
return url.endsWith('/') ? url : `${url}/`
|
||
}
|
||
|
||
function resolveApiEnv() {
|
||
// 优先读取 env.js 配置文件
|
||
const fileEnv = envConfig?.apiEnv
|
||
if (fileEnv) {
|
||
const mapped = ENV_ALIAS[fileEnv.toLowerCase()]
|
||
if (mapped) {
|
||
// #ifdef APP-PLUS || H5 || MP-ALIPAY
|
||
console.log('[API Config] 使用 env.js 配置:', fileEnv, '=>', mapped)
|
||
// #endif
|
||
return mapped
|
||
}
|
||
}
|
||
|
||
// 其次读取环境变量
|
||
const runtimeEnv =
|
||
typeof process !== 'undefined' && process?.env
|
||
? process.env.UNI_APP_API_ENV || process.env.NODE_ENV
|
||
: ''
|
||
const aliasKey = runtimeEnv ? runtimeEnv.toLowerCase() : ''
|
||
const env = ENV_ALIAS[aliasKey] || 'prod'
|
||
// #ifdef APP-PLUS || H5 || MP-ALIPAY
|
||
console.log('[API Config] 使用环境变量:', runtimeEnv, '=>', env)
|
||
// #endif
|
||
return env
|
||
}
|
||
|
||
const API_ENV = resolveApiEnv()
|
||
|
||
// API 基础地址(根据当前环境自动判定)
|
||
export const API_BASE_URL = normalizeBaseUrl(API_TARGETS[API_ENV] || API_TARGETS.prod)
|
||
|
||
// 输出当前配置信息(便于调试)
|
||
// #ifdef APP-PLUS || H5 || MP-ALIPAY
|
||
console.log('[API Config] 当前环境:', API_ENV)
|
||
console.log('[API Config] API_BASE_URL:', API_BASE_URL)
|
||
// #endif
|
||
|
||
// 当前 API 环境(local / prod)
|
||
export function getApiEnv() {
|
||
return API_ENV
|
||
}
|
||
|
||
// 导出完整的 API URL 构建函数
|
||
// H5环境下:local / prod 均直接使用完整URL,避免依赖本地代理
|
||
// 其他环境使用完整URL
|
||
export function getApiUrl(path = '') {
|
||
const apiPath = path.startsWith('/') ? path : `/${path}`
|
||
// #ifdef H5
|
||
// H5环境下,local / prod 都返回完整URL,确保 prod 时直接请求远程服务器
|
||
const fullPath = apiPath.startsWith('/') ? apiPath.slice(1) : apiPath
|
||
const fullUrl = `${API_BASE_URL}${fullPath}`
|
||
// #ifdef APP-PLUS || H5 || MP-ALIPAY
|
||
console.log(`[API Config] H5环境(${API_ENV})直接使用完整URL:`, fullUrl)
|
||
// #endif
|
||
return fullUrl
|
||
// #endif
|
||
// #ifndef H5
|
||
// 其他环境使用完整URL
|
||
const fullPath = apiPath.startsWith('/') ? apiPath.slice(1) : apiPath
|
||
const fullUrl = `${API_BASE_URL}${fullPath}`
|
||
// #ifdef APP-PLUS || H5 || MP-ALIPAY
|
||
console.log('[API Config] 非H5环境使用完整URL:', fullUrl)
|
||
// #endif
|
||
return fullUrl
|
||
// #endif
|
||
}
|