fix: cors

This commit is contained in:
2026-04-13 17:56:00 +08:00
parent 962209617f
commit ba7a014fbd
4 changed files with 45 additions and 0 deletions

View File

@@ -15,3 +15,10 @@ AMAP_MCP_AUTH_HEADER_VALUE=
# Route planning guardrails
ROUTE_MAX_PERMUTATIONS=20
# CORS
CORS_ALLOW_ORIGINS=http://localhost,http://127.0.0.1
CORS_ALLOW_ORIGIN_REGEX=https?://(localhost|127\.0\.0\.1)(:\d+)?$
CORS_ALLOW_CREDENTIALS=false
CORS_ALLOW_METHODS=GET,POST,OPTIONS
CORS_ALLOW_HEADERS=*

View File

@@ -37,6 +37,7 @@
- 已新增前端对接文档 `docs/frontend_api.md`
- 已补充上游 timeout 配置和 504 错误映射,避免外部超时被混淆为普通 500。
- 已修正 `stops` 非空校验,并更新前端文档中 `deep_links``summary` 的语义边界说明。
- 已为 FastAPI 增加可配置 CORS 中间件,默认允许本地 `localhost/127.0.0.1` 任意端口联调。
## 下一步建议

View File

@@ -17,6 +17,15 @@
http://127.0.0.1:8000
```
### 2.1 CORS
当前服务已启用 CORS。
- 默认允许本地开发来源:`localhost``127.0.0.1` 的任意端口
- 当前默认允许的方法:`GET``POST``OPTIONS`
- 当前默认允许所有请求头
- 如果前端部署到其他域名,需要后端调整 `.env` 中的 CORS 配置
## 3. 健康检查
### 3.1 请求

28
main.py
View File

@@ -1,12 +1,40 @@
import os
import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from openai import APITimeoutError
from fastapi.middleware.cors import CORSMiddleware
from schemas import RoutePlanRequest, RoutePlanResult
from agent import ConfigurationError, GuardrailError, run_route_plan
load_dotenv()
def _csv_env(name: str, default: str) -> list[str]:
raw_value = os.getenv(name, default)
return [item.strip() for item in raw_value.split(",") if item.strip()]
def _bool_env(name: str, default: bool) -> bool:
raw_value = os.getenv(name, "true" if default else "false").strip().lower()
return raw_value in {"1", "true", "yes", "on"}
app = FastAPI(title="Geo Route Agent", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=_csv_env("CORS_ALLOW_ORIGINS", "http://localhost,http://127.0.0.1"),
allow_origin_regex=os.getenv(
"CORS_ALLOW_ORIGIN_REGEX",
r"https?://(localhost|127\.0\.0\.1)(:\d+)?$",
),
allow_credentials=_bool_env("CORS_ALLOW_CREDENTIALS", False),
allow_methods=_csv_env("CORS_ALLOW_METHODS", "GET,POST,OPTIONS"),
allow_headers=_csv_env("CORS_ALLOW_HEADERS", "*"),
)
@app.post("/route/plan", response_model=RoutePlanResult)
async def route_plan(request: RoutePlanRequest) -> RoutePlanResult: