CloudFormation配置Swagger API遇CORS错误:无效映射表达式参数
错误原因与修复方案
一、直接修复当前OPTIONS端点的错误
你的错误源于Swagger 2.0响应头的语法错误:在定义OPTIONS的200响应头时,错误地嵌套了schema字段。Swagger 2.0要求响应头直接通过type指定类型,不需要嵌套schema层级。
修正后的OPTIONS部分代码如下:
options: consumes: - application/json produces: - application/json responses: '200': description: Default response headers: Access-Control-Allow-Headers: type: string Access-Control-Allow-Methods: type: string Access-Control-Allow-Origin: type: string x-amazon-apigateway-integration: type: mock requestTemplates: application/json: | {"statusCode" : 200} responses: default: statusCode: '200' responseParameters: method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" method.response.header.Access-Control-Allow-Methods: "'OPTIONS,POST,GET,PUT,DELETE,PATCH'" method.response.header.Access-Control-Allow-Origin: "'*'"
二、更简便的CORS启用方式(推荐)
使用SAM框架的Cors属性可以自动配置CORS,无需手动编写OPTIONS端点,大幅简化配置:
修改AWS::Serverless::Api的Properties,添加Cors配置:
LogUserActivityApi: Type: AWS::Serverless::Api DependsOn: LogUserActivityFunction Properties: Name: !Join [ "", [ "log-user-activity-", !Ref environment ]] Description: General api to log user activity StageName: !Join [ "", [ !Ref environment, "stage"]] # 添加以下CORS配置 Cors: AllowHeaders: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" AllowMethods: "'OPTIONS,POST,GET,PUT,DELETE,PATCH'" AllowOrigin: "'*'" Auth: DefaultAuthorizer: MyCognitoAuthorizer Authorizers: MyCognitoAuthorizer: UserPoolArn: !Ref CognitoUserPoolArn DefinitionBody: swagger: 2.0 info: version: "1.0" title: "log-user-activity" basePath: !Join [ "", [ "/", !Ref environment, "stage" ]] schemes: - "https" paths: /: get: responses: {} x-amazon-apigateway-integration: uri: Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LogUserActivityFunction.Arn}/invocations passthroughBehavior: "when_no_match" httpMethod: "POST" type: "aws_proxy" /log-user-activity: post: consumes: - application/json produces: - application/json responses: {} x-amazon-apigateway-integration: uri: Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LogUserActivityFunction.Arn}/invocations passthroughBehavior: "when_no_match" httpMethod: "POST" type: "aws_proxy"
添加Cors属性后,SAM会自动为所有资源创建OPTIONS端点并配置正确的CORS响应头,无需再手动编写OPTIONS部分。
额外说明
如果API需要更精细的CORS控制(比如特定域名而非*),可以调整AllowOrigin的值为具体域名,例如"'https://yourdomain.com'"。同时,若使用lambda proxy集成,需确保Lambda函数的响应中也返回对应的CORS头,不过通过SAM的Cors配置,API Gateway会自动处理OPTIONS请求的响应。
内容的提问来源于stack exchange,提问作者JustANoob
相关产品推荐
相关产品推荐

