怎样在 FastAPI 配置 CORSMiddleware?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
给应用添加 CORSMiddleware,明确允许的来源、方法、请求头和是否携带凭据。来源包含协议、主机和端口。开发页面与 API 端口不同也可能是跨源。
讲清原理
浏览器有时先发 OPTIONS 预检,再决定是否发送业务请求。CORS 控制浏览器是否可跨源访问响应,服务端还要独立做认证、授权与适用的 CSRF 防护。
例子与易错点
示例测试允许来源的预检,以及不在列表中的来源无法通过同一策略。配置允许凭据时使用明确来源。
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.org"],
allow_credentials=True,
allow_methods=["POST"],
allow_headers=["Content-Type"],
)
with TestClient(app) as client:
preflight = {"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "Content-Type"}
allowed = client.options("/notes", headers={**preflight, "Origin": "https://app.example.org"})
denied = client.options("/notes", headers={**preflight, "Origin": "https://other.example.org"})
assert allowed.status_code == 200
assert allowed.headers["Access-Control-Allow-Origin"] == "https://app.example.org"
assert allowed.headers["Access-Control-Allow-Credentials"] == "true"
assert denied.status_code == 400 and "Access-Control-Allow-Origin" not in denied.headers
print("allowed origin: 200; unknown origin: 400")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。