Python Falcon 简明教程
Python Falcon - CORS
"Cross-Origin Resource Sharing" (CORS) 是指运行在某个客户端浏览器上的前端应用程序尝试通过 JavaScript 代码与后端通信的情况,并且后端与前端处于不同的“来源”中。这里的来源是协议、域名和端口号的组合。因此, http://localhost 和 https://localhost 有不同的来源。
"Cross-Origin Resource Sharing" (CORS) is a situation when a frontend application that is running on one client browser tries to communicate with a backend through JavaScript code, and the backend is in a different "origin"than the frontend. The origin here is a combination of protocol, domain name and port numbers. As a result, http://localhost and https://localhost have different origins.
如果具有一个来源的 URL 的浏览器发送从另一个来源执行 JavaScript 代码的请求,则浏览器会发送 OPTIONS http 请求。如果后端通过发送适当的标头授权来自此其他来源的通信,它将允许前端的 JavaScript 将其请求发送到后端。
If the browser with URL of one origin sends request for execution of JavaScript code from another origin, the browser sends OPTIONS http request. If the backend authorizes the communication from this different origin by sending the appropriate headers it will let the JavaScript in the frontend send its request to the backend.
若要为所有响应启用 CORS 策略,则应将 Falcon 应用配置如下所示:
To enable the CORS policy for all responses, the Falcon app is configured as follows −
from falcon import App
app=App(cors_enable=True)
若要明确指定允许的源,请导入 CORSMiddleware ,并将源列表添加到应用中间件中,同时附带各自的凭据。
To specify explicitly the allowed origins, import CORSMiddleware and add the list of origins to the app’s middleware, along with respective credentials.
from falcon import App
app = falcon.App(middleware=falcon.CORSMiddleware(allow_origins='example.com', allow_credentials='*')