Files
ai_dianshang/web/ENV_CONFIG.txt
2025-11-28 15:18:10 +08:00

165 lines
4.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

==========================================
API环境自动检测配置说明
==========================================
## 1. 自动环境检测规则
系统会根据当前访问的URL自动判断调用哪个后端
### 开发环境(自动检测)
- 访问地址localhost 或 127.0.0.1
- 后端地址http://localhost:8080/api/v1
- 示例http://localhost:8080/login.html
### 生产环境(自动检测)
- 访问地址:除 localhost/127.0.0.1 以外的域名
- 后端地址:自动使用当前域名 + /api/v1
- 示例https://www.example.com → https://www.example.com/api/v1
## 2. 手动配置(用于特殊调试场景)
### 方法一:浏览器控制台
打开浏览器控制台F12输入以下命令
# 查看当前配置
API_DEBUG.getConfig()
# 设置自定义后端地址
API_DEBUG.setBaseURL('http://192.168.1.100:8080/api/v1')
# 重置为自动检测
API_DEBUG.resetBaseURL()
# 测试后端连接
API_DEBUG.testConnection()
# 查看帮助
API_DEBUG.help()
### 方法二:测试页面
访问http://localhost:8080/api-test.html
在页面中可以可视化地配置和测试
## 3. 常见使用场景
### 场景1本地开发
- 前端http://localhost:8080
- 后端http://localhost:8080Go后端
- 配置:无需配置,自动检测
### 场景2本地开发但后端在其他机器
- 前端http://localhost:8080
- 后端http://192.168.1.100:8080
- 配置API_DEBUG.setBaseURL('http://192.168.1.100:8080/api/v1')
### 场景3生产环境
- 前端https://www.yoursite.com
- 后端https://www.yoursite.com
- 配置:无需配置,自动检测
## 4. 启动步骤
### 开发环境启动
1. 启动后端:
cd d:\project\Work\dianshang\server
go run cmd/main.go
2. 启动前端(任选一种):
cd d:\project\Work\dianshang\web
# Python
python -m http.server 8080
# Node.js
npx http-server -p 8080
3. 访问http://localhost:8080/login.html
## 5. 调试技巧
1. 查看环境信息
打开浏览器控制台,会自动显示:
[API] 当前环境: 开发环境
[API] 后端地址: http://localhost:8080/api/v1
2. 测试API连接
API_DEBUG.testConnection()
3. 查看网络请求
浏览器F12 → Network标签 → 查看API请求
## 6. 注意事项
⚠️ 手动配置会保存在 localStorage 中
- 如果遇到问题,可以使用 API_DEBUG.resetBaseURL() 重置
- 清除浏览器缓存也会清除手动配置
⚠️ 跨域问题
- 开发环境后端已配置CORS支持 localhost 访问
- 生产环境需要在后端CORS配置中添加生产域名
⚠️ HTTPS 和 HTTP 混合
- 如果前端使用 HTTPS后端也必须使用 HTTPS
- 浏览器会阻止 HTTPS 页面访问 HTTP 接口
## 7. 故障排查
问题1API调用失败提示CORS错误
解决检查后端CORS配置确保允许当前域名
问题2本地开发时无法访问后端
解决:
1. 确认后端服务已启动go run cmd/main.go
2. 访问 http://localhost:8080/health 检查后端是否运行
3. 检查端口是否被占用
问题3生产环境API路径不正确
解决:
1. 检查Nginx配置确保正确代理 /api/v1
2. 或使用 API_DEBUG.setBaseURL() 手动设置完整后端地址
## 8. 生产环境部署建议
### 方案1前后端同域名推荐
```nginx
server {
listen 80;
server_name www.example.com;
# 前端静态文件
location / {
root /var/www/web;
try_files $uri $uri/ /index.html;
}
# 后端API代理
location /api/v1 {
proxy_pass http://localhost:8080/api/v1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
此时前端会自动检测并使用https://www.example.com/api/v1
### 方案2前后端分离部署
如果后端独立部署(如 api.example.com需要修改 api.js
在生产环境判断中,返回固定的后端地址:
```javascript
// 生产环境
return 'https://api.example.com/api/v1';
```
==========================================
更多问题请查看项目文档
==========================================