Vue3 + ECharts-GL 2.0.8 实战:手把手教你打造可交互的离线3D地图(附新疆JSON数据)
2026/6/4 14:29:43
我分3 层给你讲清楚:
① 这段 CORS 代码到底干嘛
② FastAPI 和 Vue 是如何“前后端交互”的
③ 浏览器在中间扮演了什么角色(为什么不加 CORS 会报错)
你看完这部分,前后端交互在你脑子里会是“透明的”。
你的代码 👇
fromfastapi.middleware.corsimportCORSMiddleware 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 是“浏览器的安全策略”
Vue 用 HTTP 请求调用 FastAPI 的 API
就像:
浏览器 → HTTP → FastAPI → 数据库
Vue (localhost:8080) | | HTTP 请求(axios / fetch) ↓ FastAPI (localhost:8000) | | SQLAlchemy ↓ PostgreSQL (Docker / Linux)axios.post("http://localhost:8000/api/v1/stats",{category:"CI_JOB",value:10})⚠️ 这一步发生在浏览器里(不是 Node)
| 项目 | Vue | FastAPI |
|---|---|---|
| 协议 | http | http |
| 域名 | localhost | localhost |
| 端口 | 8080 | 8000 |
👉端口不同 = 跨域
于是:
“你允许
localhost:8080调用你吗?”
你的代码让 FastAPI 回答:
Access-Control-Allow-Origin: http://localhost:8080 Access-Control-Allow-Methods: * Access-Control-Allow-Headers: *浏览器一看:
“OK,是合法的 👍”
FastAPI 路由执行:
@router.post("/stats")defcreate_stat(...):...数据写入 PostgreSQL
{"id":1,"category":"CI_JOB","value":10,"created_at":"2025-01-01T12:00:00"}this.stats.push(res.data)页面自动刷新 ✔
| 角色 | 作用 |
|---|---|
| Vue | 负责 UI + 发 HTTP 请求 |
| 浏览器 | 安全检查(CORS) |
| FastAPI | 提供 API |
| PostgreSQL | 存数据 |
👉Vue ≠ 后端
👉FastAPI ≠ 前端
👉 它们只是通过HTTP 协议对话
你可能注意到:
curlhttp://localhost:8000/api/v1/stats👉 永远不会报 CORS 错
只有浏览器才实现 CORS
Postman / curl = 直接发 HTTP
Vue: http://localhost:8080 FastAPI: http://localhost:8000👉 不同端口 → 跨域 → 要 CORS
https://stats.company.com ├── / → Vue └── /api → FastAPI👉同域名、同端口
🚫根本没有跨域问题
origins=["http://localhost:8080"]allow_origins=["*"]Vue (页面) ↓ axios / fetch 浏览器(CORS 检查) ↓ FastAPI API ↓ 数据库