42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
|
|
/**
|
|||
|
|
* API 基础路径工具函数
|
|||
|
|
* 自动适配 ngrok 内网穿透和本地开发环境
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取 API 基础路径
|
|||
|
|
* @returns {string} API 基础路径
|
|||
|
|
*/
|
|||
|
|
export function getApiBaseURL() {
|
|||
|
|
// 检查是否在浏览器环境中
|
|||
|
|
if (typeof window !== 'undefined') {
|
|||
|
|
const hostname = window.location.hostname
|
|||
|
|
|
|||
|
|
// 如果当前域名包含 ngrok 或通过 Nginx 访问,使用相对路径
|
|||
|
|
if (hostname.includes('ngrok') ||
|
|||
|
|
hostname === 'localhost' ||
|
|||
|
|
hostname === '127.0.0.1' ||
|
|||
|
|
hostname.startsWith('172.22.') ||
|
|||
|
|
window.location.port === '') { // 通过 Nginx 代理访问时没有端口号
|
|||
|
|
// 通过 Nginx 访问,使用相对路径(自动适配当前域名)
|
|||
|
|
return '/api'
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 默认开发环境,使用相对路径(通过 Vite 代理)
|
|||
|
|
return '/api'
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 构建完整的 API URL
|
|||
|
|
* @param {string} path - API 路径(如 '/users' 或 'users')
|
|||
|
|
* @returns {string} 完整的 API URL
|
|||
|
|
*/
|
|||
|
|
export function buildApiURL(path) {
|
|||
|
|
const baseURL = getApiBaseURL()
|
|||
|
|
// 确保路径以 / 开头
|
|||
|
|
const cleanPath = path.startsWith('/') ? path : `/${path}`
|
|||
|
|
return `${baseURL}${cleanPath}`
|
|||
|
|
}
|
|||
|
|
|