解决跨越问题

main
mula.liu 2025-12-02 22:50:18 +08:00
parent 9c1c444397
commit 3f7a983178
3 changed files with 67 additions and 4 deletions

View File

@ -18,10 +18,17 @@ REDIS_MAX_CONNECTIONS=50
# ======================
# Application Configuration
# ======================
# CORS - Set your domain here
CORS_ORIGINS=http://your-domain.com,https://your-domain.com
# CORS - Support both internal IP access and external domain
# Format: comma-separated list of origins
# Examples:
# - Internal IP only: CORS_ORIGINS=http://192.168.1.100
# - Domain only: CORS_ORIGINS=http://your-domain.com,https://your-domain.com
# - Both IP and domain: CORS_ORIGINS=http://192.168.1.100,http://your-domain.com,https://your-domain.com
# - Allow all (development): CORS_ORIGINS=*
CORS_ORIGINS=*
# API Base URL for frontend
# Set this to your domain or IP address
VITE_API_BASE_URL=http://your-domain.com/api
# ======================

View File

@ -133,11 +133,29 @@ cosmo/
# 修改数据库密码(必须)
DATABASE_PASSWORD=your_secure_password_here
# 修改域名(必须)
# 修改 CORS 配置(支持内网 IP 和外网域名访问)
# 方式 1: 允许所有来源(开发/测试环境)
CORS_ORIGINS=*
# 方式 2: 仅允许特定 IP内网访问
CORS_ORIGINS=http://192.168.1.100
# 方式 3: 仅允许特定域名(外网访问)
CORS_ORIGINS=http://your-domain.com,https://your-domain.com
# 方式 4: 同时允许内网 IP 和外网域名(推荐生产环境)
CORS_ORIGINS=http://192.168.1.100,http://your-domain.com,https://your-domain.com
# 修改前端 API 地址(必须)
VITE_API_BASE_URL=http://your-domain.com/api
```
**重要说明**:
- `CORS_ORIGINS` 使用逗号分隔多个来源,无需引号或方括号
- 每个来源必须包含协议http:// 或 https://
- 不要在来源末尾添加斜杠
- 使用 `*` 允许所有来源(仅用于开发环境)
### 2. 初始化部署
```bash
@ -350,6 +368,35 @@ docker stats
## 🐛 故障排查
### CORS 配置错误
**错误信息**:
```
pydantic_settings.sources.SettingsError: error parsing value for field "cors_origins"
```
**原因**: CORS_ORIGINS 配置格式错误
**解决方案**:
```bash
# ✅ 正确格式(逗号分隔,无引号)
CORS_ORIGINS=http://192.168.1.100,http://domain.com,https://domain.com
# ✅ 允许所有来源
CORS_ORIGINS=*
# ❌ 错误格式(不要使用 JSON 数组格式)
CORS_ORIGINS=["http://domain.com", "https://domain.com"]
# ❌ 错误格式(不要在域名后加斜杠)
CORS_ORIGINS=http://domain.com/,https://domain.com/
```
修改 `.env.production` 后需要重启服务:
```bash
./deploy.sh --restart
```
### 服务启动失败
1. 查看日志:

View File

@ -2,7 +2,7 @@
Application configuration
"""
from pydantic_settings import BaseSettings
from pydantic import Field
from pydantic import Field, field_validator
class Settings(BaseSettings):
@ -15,6 +15,15 @@ class Settings(BaseSettings):
# CORS settings - allow all origins for development (IP access support)
cors_origins: list[str] = ["*"]
@field_validator('cors_origins', mode='before')
@classmethod
def parse_cors_origins(cls, v):
"""Parse CORS origins from comma-separated string or JSON array"""
if isinstance(v, str):
# Parse comma-separated string
return [origin.strip() for origin in v.split(',') if origin.strip()]
return v
# Cache settings
cache_ttl_days: int = 3