f946e9dd
hexiaodong
hhh
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
|
# 收银台 API 配置指南
## 概述
收银台系统(sy 文件夹)已配置为支持 **开发环境** 和 **生产环境** 的自动切换。
## 配置原理
所有 HTML 文件中的 `baseUrl` 都使用动态配置:
```javascript
baseUrl: (() => {
const currentOrigin = window.location.origin;
if (currentOrigin.includes('localhost') || currentOrigin.includes('127.0.0.1')) {
// 开发环境
return 'http://localhost:2015';
} else {
// 生产环境
return currentOrigin.replace(/:\d+$/, '');
}
})(),
```
## 环境切换逻辑
### 开发环境
- **前端地址**: `http://localhost:8888`
- **API 地址**: `http://localhost:2015` ✅ (自动检测)
### 生产环境(示例)
- **前端地址**: `https://www.ponggame.cn` 或 `https://api.ponggame.cn`
- **API 地址**: 与前端同域名 ✅ (自动检测)
- **或者**: `https://www.ponggame.cn/api` ✅ (需手动配置)
## 部署到生产环境
### 场景 1:API 和前端在同一域名(推荐)
如果生产环境配置如下:
- 前端: `https://www.ponggame.cn/sy/`
- API: `https://www.ponggame.cn/api/`
**无需修改代码**,系统会自动使用 `https://www.ponggame.cn` 作为 baseUrl。
### 场景 2:API 在不同的域名
如果 API 在独立的域名上,比如:
- 前端: `https://www.ponggame.cn/sy/`
- API: `https://api.ponggame.cn/`
需要修改配置。以 `home.html` 为例:
```javascript
baseUrl: (() => {
const currentOrigin = window.location.origin;
if (currentOrigin.includes('localhost') || currentOrigin.includes('127.0.0.1')) {
return 'http://localhost:2015';
} else if (currentOrigin.includes('ponggame.cn')) {
return 'https://api.ponggame.cn'; // ✅ 指定生产 API 地址
} else {
return currentOrigin;
}
})(),
```
## 应用此配置的文件
以下文件都已应用动态 baseUrl 配置:
- ✅ `home.html` - 主页面
- ✅ `settlement.html` - 结账页面
- ✅ `orders.html` - 订单管理页面
- ✅ `member.html` - 会员管理页面
- ✅ `login.html` - 登录页面
- ✅ `from.html` - 表单页面
## 后端 CORS 配置
确保后端的 CORS 配置包含生产环境的域名。
### ASP.NET Core 配置示例
编辑 `appsettings.json`:
```json
{
"Furion": {
"CorsAccessor": {
"WithOrigins": [
"http://localhost:8888", // 开发环境
"https://www.ponggame.cn", // 生产环境
"https://api.ponggame.cn" // 生产环境(如果不同域名)
]
}
}
}
```
## 测试方法
### 测试开发环境
```
前端地址: http://localhost:8888/home.html
预期 API: http://localhost:2015
```
### 测试生产环境
```
前端地址: https://www.ponggame.cn/sy/home.html
预期 API: https://www.ponggame.cn
```
## 常见问题
### Q: 如何验证 API 地址是否正确?
**A**: 打开浏览器控制台,执行:
```javascript
console.log('Current baseUrl:', this.baseUrl);
```
### Q: 生产环境收银台无法连接 API?
**A**: 检查以下几点:
1. 后端 CORS 配置是否包含前端域名
2. API 地址是否正确(http vs https)
3. 防火墙/安全组是否放行
### Q: 如何切换到特定的 API 服务器?
**A**: 临时修改 `baseUrl`,或在浏览器控制台执行:
```javascript
this.baseUrl = 'https://your-api-server.com';
```
## 总结
✅ **零配置开发** - 开发环境自动检测
✅ **简单部署** - 生产环境基本无需修改
✅ **灵活扩展** - 支持多域名配置
✅ **CORS 友好** - 后端配置即可兼容多个源
|