我分 3 层 给你讲清楚:
① 这段 CORS 代码到底干嘛
② FastAPI 和 Vue 是如何"前后端交互"的
③ 浏览器在中间扮演了什么角色(为什么不加 CORS 会报错)
你看完这部分,前后端交互在你脑子里会是"透明的"。
一、这段 CORS 代码是不是"用来前后端交互的"?
❌ 不完全是
✅ 它是「允许浏览器发起跨域请求」的开关
你的代码 👇
python
from fastapi.middleware.cors import CORSMiddleware
origins = ["http://localhost:8080"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
它的真实作用是:
告诉浏览器:
👉「来自
http://localhost:8080的网页👉 可以合法访问我这个 FastAPI 服务」
⚠️ 注意一句非常重要的话:
FastAPI 和 Vue 本身不需要 CORS
CORS 是"浏览器的安全策略"
二、FastAPI 和 Vue 是如何真正"交互"的?(核心原理)
🧠 本质一句话:
Vue 用 HTTP 请求调用 FastAPI 的 API
就像:
text浏览器 → HTTP → FastAPI → 数据库
三、真实的请求链路(你现在的项目)
你现在的架构是:
text
Vue (localhost:8080)
|
| HTTP 请求(axios / fetch)
↓
FastAPI (localhost:8000)
|
| SQLAlchemy
↓
PostgreSQL (Docker / Linux)
四、一步一步拆解「一次前后端交互」
① Vue 发起请求(浏览器里)
js
axios.post("http://localhost:8000/api/v1/stats", {
category: "CI_JOB",
value: 10
})
⚠️ 这一步 发生在浏览器里(不是 Node)
② 浏览器检查:跨域了吗?
| 项目 | Vue | FastAPI |
|---|---|---|
| 协议 | http | http |
| 域名 | localhost | localhost |
| 端口 | 8080 | 8000 |
👉 端口不同 = 跨域
③ 浏览器说:我不信任这个请求 😈
于是:
- 浏览器先发一个 OPTIONS 预检请求
- 问 FastAPI:
"你允许
localhost:8080调用你吗?"
④ FastAPI 的 CORS 中间件回应
你的代码让 FastAPI 回答:
http
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
浏览器一看:
"OK,是合法的 👍"
⑤ 真正的 POST / GET 请求才被发送
FastAPI 路由执行:
python
@router.post("/stats")
def create_stat(...):
...
数据写入 PostgreSQL
⑥ FastAPI 返回 JSON
json
{
"id": 1,
"category": "CI_JOB",
"value": 10,
"created_at": "2025-01-01T12:00:00"
}
⑦ Vue 拿到数据,更新页面(响应式)
js
this.stats.push(res.data)
页面自动刷新 ✔
五、关键认知:谁和谁在通信?
| 角色 | 作用 |
|---|---|
| Vue | 负责 UI + 发 HTTP 请求 |
| 浏览器 | 安全检查(CORS) |
| FastAPI | 提供 API |
| PostgreSQL | 存数据 |
👉 Vue ≠ 后端
👉 FastAPI ≠ 前端
👉 它们只是通过 HTTP 协议 对话
六、为什么 curl / Postman 不需要 CORS?
你可能注意到:
bash
curl http://localhost:8000/api/v1/stats
👉 永远不会报 CORS 错
原因:
只有浏览器才实现 CORS
Postman / curl = 直接发 HTTP
七、生产环境为什么"又不需要 CORS"?
开发环境(你现在)
text
Vue: http://localhost:8080
FastAPI: http://localhost:8000
👉 不同端口 → 跨域 → 要 CORS
生产环境(常见)
text
https://stats.company.com
├── / → Vue
└── /api → FastAPI
👉 同域名、同端口
🚫 根本没有跨域问题
八、你的这段 CORS 写法是否正确?(结论)
✅ 现在:完全正确(开发期推荐)
python
origins = ["http://localhost:8080"]
⚠️ 不推荐这样(不安全)
python
allow_origins=["*"]
九、给你一张「前后端交互心智模型」
Vue (页面)
↓ axios / fetch
浏览器(CORS 检查)
↓
FastAPI API
↓
数据库