我有一個由 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 配置。
- 它提供對
OPTIONS具有適當 CORS 相關標頭的請求的回應,但 - 似乎它不會
GET <api>/comments/{post_slug}使用適當的 CORS 標頭對請求的回應進行水合
這使得CORSCDK 構造中的配置選項不是特別有用- 因為我忽略該設定并改為手動配置來自我的 Lambda 的 OPTIONS 回應似乎更明智,將其更改為:
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 來配置回應以正確補充。
uj5u.com熱心網友回復:
CDK 為該OPTIONS方法生成的代碼使用回應覆寫 - https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html
此選項在用于 GET 方法的 lambda 代理集成中不可用。除了在 lambda 源代碼級別計算 CORS 標頭之外,我確實沒有找到任何其他選項。
PS:我寫了https://milangatyas.com/Blog/Detail/14/setup-cors-for-amazon-api-gateway-via-aws-cdk在那里你可以獲得更詳細的資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322127.html
標籤:打字稿 亚马逊网络服务 亚马逊云形成 aws-api-网关 aws-cdk
