本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
CorsConfiguration
为 API Gateway API 管理跨源资源共享 (CORS) 使用字符串指定允许使用的域,或使用其他 Cors 配置指定词典。
注意
CORS Amazon SAM 需要修改你的 OpenAPI 定义。在中创建一个内联 OpenAPI 定义DefinitionBody
以启用 CORS。如果在 CorsConfiguration
OpenAPI 定义中和属性级别设置了,则将其 Amazon SAM 合并。属性级别优先于 OpenAPI 定义。
有关 CORS 的更多信息,请参阅《API Gateway 开发人员指南》中的为 API Gateway REST API 资源启用 CORS。
语法
要在 Amazon Serverless Application Model (Amazon SAM) 模板中声明此实体,请使用以下语法。
YAML
AllowCredentials:
Boolean
AllowHeaders:String
AllowMethods:String
AllowOrigin:String
MaxAge:String
属性
-
AllowCredentials
-
表示是否允许请求包含凭证的布尔值。
类型:布尔值
必需:否
Amazon CloudFormation 兼容性:此属性是独有的 Amazon SAM ,没有 Amazon CloudFormation 等效属性。
-
AllowHeaders
-
允许的标头字符串。
类型:字符串
必需:否
Amazon CloudFormation 兼容性:此属性是独有的 Amazon SAM ,没有 Amazon CloudFormation 等效属性。
-
AllowMethods
-
包含允许的 HTTP 方法的字符串。
类型:字符串
必需:否
Amazon CloudFormation 兼容性:此属性是独有的 Amazon SAM ,没有 Amazon CloudFormation 等效属性。
-
AllowOrigin
-
允许的源字符串。
类型:字符串
必需:是
Amazon CloudFormation 兼容性:此属性是独有的 Amazon SAM ,没有 Amazon CloudFormation 等效属性。
-
MaxAge
-
包含缓存 CORS 预检请求的秒数的字符串。
类型:字符串
必需:否
Amazon CloudFormation 兼容性:此属性是独有的 Amazon SAM ,没有 Amazon CloudFormation 等效属性。
示例
CorsConfiguration
跨域资源共享配置示例。这只是 Amazon SAM 模板文件的一部分,其中显示了配置了 CORS 的AWS::Serverless::Api定义和. AWS::Serverless::Function 如果您使用 Lambda 代理集成或 HTTP 代理集成,则您的后端必须返回Access-Control-Allow-Origin
Access-Control-Allow-Methods
、和Access-Control-Allow-Headers
标头。
YAML
Resources: ApiGatewayApi: Type: AWS::Serverless::Api Properties: StageName: Prod Cors: AllowMethods: "'POST, GET'" AllowHeaders: "'X-Forwarded-For'" AllowOrigin: "'www.example.com'" MaxAge: "'600'" AllowCredentials: true ApiFunction: # Adds a GET method at the root resource via an Api event Type: AWS::Serverless::Function Properties: Events: ApiEvent: Type: Api Properties: Path: / Method: get RestApiId: Ref: ApiGatewayApi Runtime: python3.10 Handler: index.handler InlineCode: | import json def handler(event, context): return { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Origin': 'www.example.com', 'Access-Control-Allow-Methods': 'POST, GET' }, 'body': json.dumps('Hello from Lambda!') }