FastAPI 中如何使用 CORSMiddleware 处理跨域资源共享 (CORS)?

· 约 3 分钟读完 · 第 73 / 128 章

推荐答案

在 FastAPI 中,可以使用 CORSMiddleware 来处理跨域资源共享 (CORS)。以下是一个示例代码:

在这个示例中,CORSMiddleware 被添加到 FastAPI 应用中,允许来自 https://example.com 和 https://another-example.com 的跨域请求。allow_credentials=True 允许跨域请求携带凭证(如 cookies),allow_methods=["*"] 允许所有 HTTP 方法,allow_headers=["*"] 允许所有 HTTP 头。

本题详细解读

什么是 CORS?

跨域资源共享 (CORS) 是一种机制,允许网页从不同的域请求资源。浏览器出于安全考虑,默认会阻止跨域请求。CORS 通过在 HTTP 头中添加特定的字段来允许或拒绝跨域请求。

FastAPI 中的 CORSMiddleware

FastAPI 提供了 CORSMiddleware 来简化 CORS 的处理。通过将 CORSMiddleware 添加到 FastAPI 应用中,可以轻松配置允许的源、方法、头等。

CORSMiddleware 参数详解

  • allow_origins: 允许的源列表。可以是一个字符串列表,如 ["https://example.com"],或者使用 "*" 允许所有源。
  • allow_credentials: 是否允许跨域请求携带凭证(如 cookies)。默认为 False。
  • allow_methods: 允许的 HTTP 方法列表。可以是一个字符串列表,如 ["GET", "POST"],或者使用 "*" 允许所有方法。
  • allow_headers: 允许的 HTTP 头列表。可以是一个字符串列表,如 ["X-Custom-Header"],或者使用 "*" 允许所有头。

示例代码解析

在示例代码中,CORSMiddleware 被配置为允许来自 https://example.com 和 https://another-example.com 的跨域请求。allow_credentials=True 允许跨域请求携带凭证,allow_methods=["*"] 允许所有 HTTP 方法,allow_headers=["*"] 允许所有 HTTP 头。

通过这种方式,FastAPI 应用可以轻松处理跨域请求,确保前端应用能够安全地与后端 API 进行交互。