API_CONFIG.md 3.46 KB

收银台 API 配置指南

概述

收银台系统(sy 文件夹)已配置为支持 开发环境生产环境 的自动切换。

配置原理

所有 HTML 文件中的 baseUrl 都使用动态配置:

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.cnhttps://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 为例:

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

{
  "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: 打开浏览器控制台,执行:

console.log('Current baseUrl:', this.baseUrl);

Q: 生产环境收银台无法连接 API?

A: 检查以下几点:

  1. 后端 CORS 配置是否包含前端域名
  2. API 地址是否正确(http vs https)
  3. 防火墙/安全组是否放行

Q: 如何切换到特定的 API 服务器?

A: 临时修改 baseUrl,或在浏览器控制台执行:

this.baseUrl = 'https://your-api-server.com';

总结

零配置开发 - 开发环境自动检测 ✅ 简单部署 - 生产环境基本无需修改 ✅ 灵活扩展 - 支持多域名配置 ✅ CORS 友好 - 后端配置即可兼容多个源