CORS = Cross-Origin Resource Sharing (跨域资源共享)

问题背景 :浏览器有同源策略—— 网页来自 a.com ,就只能请求 a.com 的 API,不能请求 b.com 的 API(防止恶意网站窃取数据)。

网页地址:http://localhost:8000          (前端)
API 地址:http://localhost:8000/api/...   (后端)
→ 同源(协议+域名+端口都相同)→ 允许

网页地址:http://localhost:3000          (前端开发服务器)
API 地址:http://localhost:8000/api/...   (后端)
→ 不同源(端口不同)→ 浏览器默认阻止!

CORS 中间件的作用 :在后端响应头里加 Access-Control-Allow-Origin: * ,告诉浏览器「我允许任何网站调用我的 API」。

allow_origins=["*"]          # 允许哪些网站调用(* = 全部)
allow_credentials=True       # 是否允许带 Cookie
allow_methods=["*"]          # 允许哪些 HTTP 方法(GET/POST/...)
allow_headers=["*"]          # 允许哪些请求头
```生产环境不要用 * ,要写明允许的域名,如 ["https://myapp.com"] 。