FastAPI 教程翻译 - 用户指南 28 - CORS(跨域资源共享)

FastAPI 教程翻译 - 用户指南 28 - CORS(跨域资源共享)

FastAPI Tutorial - User Guide - CORS (Cross-Origin Resource Sharing)

CORS or “Cross-Origin Resource Sharing” refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different “origin” than the frontend.

CORS 或『跨域资源共享』 指的是在浏览器中运行的前端具有可通信的 JavaScript 代码的情况后端,而后端与前端的来源不同。

Origin

起源

An origin is the combination of protocol (http, https), domain (myapp.com, localhost, localhost.tiangolo.com), and port (80, 443, 8080).

来源是通讯协定(httphttps),网域(myapp.comlocalhostlocalhost.tiangolo.com)和通讯埠(804438080)。

So, all these are different origins:

因此,所有这些都是不同的来源:

  • http://localhost
  • https://localhost
  • http://localhost:8080

Even if they are all in localhost, they use different protocols or ports, so, they are different “origins”.

即使它们都在 localhost 中,它们也使用不同的协议或端口,因此它们是不同的『来源』。

Steps

步骤

So, let’s say you have a frontend running in your browser at http://localhost:8080, and its JavaScript is trying to communicate with a backend running at http://localhost (because we don’t specify a port, the browser will assume the default port 80).

因此,假设您的浏览器中的前端运行在 http://localhost:8080,并且其 JavaScript 试图与运行在 http://localhost 的后端进行通信(因为我们未指定端口,浏览器将采用默认端口 80)。

Then, the browser will send an HTTP OPTIONS request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (http://localhost:8080) then the browser will let the JavaScript in the frontend send its request to the backend.

然后,浏览器将向后端发送 HTTP OPTIONS 请求,如果后端发送了适当的标头以授权来自此不同来源(http://localhost:8080)的通信,则浏览器将允许 JavaScript 进入前端将其请求发送到后端。

To achieve this, the backend must have a list of “allowed origins”.

为此,后端必须具有『允许的来源』列表。

In this case, it would have to include http://localhost:8080 for the frontend to work correctly.

在这种情况下,前端必须包含 http:// localhost:8080 才能正常工作。

Wildcards

通配符

It’s also possible to declare the list as "*" (a “wildcard”) to say that all are allowed.

也可以将列表声明为 *(一种『通配符』),以表示所有内容都允许。

But that will only allow certain types of communication, excluding everything that involves credentials: Cookies, Authorization headers like those used with Bearer Tokens, etc.

但这仅允许某些类型的通信,不包括涉及凭据的所有内容:Cookie,授权 headers(如与 Bearer 令牌一起使用的)等。

So, for everything to work correctly, it’s better to specify explicitly the allowed origins.

因此,为了使一切正常工作,最好明确指定允许的来源。

Use CORSMiddleware

使用 CORSMiddleware

You can configure it in your FastAPI application using the CORSMiddleware.

您可以使用 CORSMiddleware 在您的 FastAPI 应用程序中对其进行配置。

  • Import CORSMiddleware.

    导入 CORSMiddleware

  • Create a list of allowed origins (as strings).

    创建允许的来源列表(以字符串形式)。

  • Add it as a “middleware” to your FastAPI application.

    将其作为『中间件』添加到您的 FastAPI 应用程序中。

You can also specify if your backend allows:

您还可以指定后端是否允许:

  • Credentials (Authorization headers, Cookies, etc).

    凭据(授权 headers,Cookie 等)。

  • Specific HTTP methods (POST, PUT) or all of them with the wildcard "*".

    特定的 HTTP 方法(POSTPUT)或所有通配符 *

  • Specific HTTP headers or all of them with the wildcard "*".

    特定的 HTTP headers 或所有通配符 *

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def main():
    return {"message": "Hello World"}

The default parameters used by the CORSMiddleware implementation are restrictive by default, so you’ll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.

默认情况下,CORSMiddleware 实现使用的默认参数是限制性的,因此您需要显式启用特定的来源,方法或标头,以便允许浏览器在跨域上下文中使用它们。

The following arguments are supported:

支持以下参数:

  • allow_origins - A list of origins that should be permitted to make cross-origin requests. E.g. ['https://example.org', 'https://www.example.org']. You can use ['*'] to allow any origin.

    allow_origins - 应该允许进行跨域请求的起源列表。例如。 ['https://example.org', 'https://www.example.org']。您可以使用 ['*'] 允许任何来源。

  • allow_origin_regex - A regex string to match against origins that should be permitted to make cross-origin requests. eg. 'https://.*\.example\.org'.

    allow_origin_regex - 一个正则表达式字符串,与应允许进行跨域请求的来源相匹配。例如。 'https://.*\.example\.org'

  • allow_methods - A list of HTTP methods that should be allowed for cross-origin requests. Defaults to ['GET']. You can use ['*'] to allow all standard methods.

    allow_methods - 跨域请求应允许的 HTTP 方法列表。默认为 ['GET']。您可以使用 ['*'] 来允许所有标准方法。

  • allow_headers - A list of HTTP request headers that should be supported for cross-origin requests. Defaults to []. You can use ['*'] to allow all headers. The Accept, Accept-Language, Content-Language and Content-Type headers are always allowed for CORS requests.

    allow_headers - 跨域请求应支持的 HTTP 请求 headers 列表。默认为 []。您可以使用 ['*'] 来允许所有标题。对于 CORS 请求,始终允许使用 AcceptAccept-LanguageContent-LanguageContent-Type headers。

  • allow_credentials - Indicate that cookies should be supported for cross-origin requests. Defaults to False.

    allow_credentials - 指示跨域请求应支持 cookie。默认为 False

  • expose_headers - Indicate any response headers that should be made accessible to the browser. Defaults to [].

    expose_headers - 指示应被浏览器访问的所有响应头。默认为 []

  • max_age - Sets a maximum time in seconds for browsers to cache CORS responses. Defaults to 60.

    max_age - 设置浏览器缓存 CORS 响应的最长时间(以秒为单位)。默认为 60

The middleware responds to two particular types of HTTP request…

中间件响应两种特定类型的 HTTP 请求……

CORS preflight requests

CORS 预检请求

These are any OPTIONS request with Origin and Access-Control-Request-Method headers.

这些是带有 OriginAccess-Control-Request-Method headers 的任何 OPTIONS 请求。

In this case the middleware will intercept the incoming request and respond with appropriate CORS headers, and either a 200 or 400 response for informational purposes.

在这种情况下,中间件将拦截传入的请求并使用适当的 CORS headers 进行响应,并出于信息目的而响应 200400

Simple requests

简单请求

Any request with an Origin header. In this case the middleware will pass the request through as normal, but will include appropriate CORS headers on the response.

任何带有 Origin header 的请求。在这种情况下,中间件将照常通过请求,但在响应上将包含适当的 CORS headers。

More info

更多信息

For more info about CORS, check the Mozilla CORS documentation.

有关 CORS 的更多信息,请查看 Mozilla CORS 文档

Technical Details

技术细节

You could also use from starlette.middleware.cors import CORSMiddleware.

您也可以使用 from starlette.middleware.cors import CORSMiddleware

FastAPI provides several middlewares in fastapi.middleware just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette.

FastAPIfastapi.middleware 中提供了几种中间件,以方便开发人员。但是大多数可用的中间件直接来自 Starlette。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值