使用 Python CDK 在 API 网关上启用 CORS

Enable CORS on API Gateway with Python CDK

我在 python cdk 中定义了一个 API 网关,它将接受 CURL Restful 从 S3 存储桶上传/读取/删除文件的请求:

api = api_gw.RestApi(self, "file-api",
                  rest_api_name="File REST Service")
        
        file = api.root.add_resource("{id}")
        
        get_files_integration = api_gw.LambdaIntegration(handler,
                request_templates={"application/json": '{ "statusCode": "200" }'})
        post_file_integration = api_gw.LambdaIntegration(handler)
        get_file_integration = api_gw.LambdaIntegration(handler)
        delete_file_integration = api_gw.LambdaIntegration(handler)
        
        api.root.add_method("GET", get_files_integration, authorization_type=api_gw.AuthorizationType.COGNITO, authorizer=auth)
        file.add_method("POST", post_file_integration);     # POST /{id}
        file.add_method("GET", get_file_integration);       # GET /{id}
        file.add_method("DELETE", delete_file_integration); # DELETE /{id}  

是否可以在 API 网关上启用 CORS,以便它执行飞行前检查并允许从另一台机器上的本地主机进行外部访问?

我尝试使用我能找到的文档中定义的现有 add_core_preflight() 方法,但我相信这可能从 CDK 2.0 开始不再有效。

是的,IResource.add_cors_preflight() 正是这样做的。

您还可以使用 default_cors_preflight_options attribute of RestApi.

指定默认 CORS 配置

以下是 docs 中的示例。它们在 Typescript 中,但在 Python.

中同样有效

The following example will enable CORS for all methods and all origins on all resources of the API:

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})

The following example will add an OPTIONS method to the myResource API resource, which only allows GET and PUT HTTP requests from the origin https://amazon.com.

declare const myResource: apigateway.Resource;

myResource.addCorsPreflight({
  allowOrigins: [ 'https://amazon.com' ],
  allowMethods: [ 'GET', 'PUT' ]
});