【发布时间】:2021-10-18 20:00:33
【问题描述】:
我有一个由 AWS ApiGateway 提供的 API,由 AWS Lambda 函数支持并使用 CDK 进行预置。 API 已使用默认 CORS 设置进行配置:
const api = new apiGateway.RestApi(this, "comments-api", {
defaultCorsPreflightOptions: { allowOrigins: apiGateway.Cors.ALL_ORIGINS }
})
const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")
comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))
这似乎只为我的 API 提供了部分 CORS 配置。
- 它使用适当的 CORS 相关标头提供对
OPTIONS请求的响应,但 - 似乎它没有使用适当的 CORS 标头对对
GET <api>/comments/{post_slug}的请求的响应进行水合
这使得 CDK 构造中的 CORS 配置选项不是特别有用 - 因为我似乎更明智地忽略该设置,而是手动配置一个 OPTIONS来自我的 Lambda 的响应,将其更改为:
const api = new apiGateway.RestApi(this, "comments-api")
const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")
comment.addMethod("GET", new apiGateway.LambdaIntegration(listCommentsFunction))
comment.addMethod("OPTIONS", new apiGateway.LambdaIntegration(listCommentsFunction))
然后确保我的 lambda 始终以正确的标头响应。如果我不这样做,那么我将使用 两种 不同的机制使用 CORS 标头来补充我的响应; CDK 堆栈配置和显式处理程序逻辑。这感觉像是一种气味。
出于这个原因,我想知道我是否配置错误,并且有一种方法可以使用 CDK 来配置响应以正确补水。
【问题讨论】:
标签: typescript amazon-web-services amazon-cloudformation aws-api-gateway aws-cdk