You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CDK正确配置AWS APIGateway的跨域CORS规则

问题解答

你没有配置错误,defaultCorsPreflightOptions 的设计定位就是仅处理OPTIONS预检请求的CORS响应头,不会自动注入到GET/POST等业务请求的响应中,这是APIGateway的原生机制决定的,不是CDK的功能缺陷。

目前有两种成熟的实现方案可选:

方案1:保留CDK自动处理OPTIONS,仅在Lambda中返回业务响应CORS头(推荐)

这是生产环境最常用的方案,代码量最小,维护成本最低:

  • 继续使用defaultCorsPreflightOptions配置,让APIGateway自动响应所有OPTIONS预检请求,不需要手动给资源加OPTIONS方法,也不需要在Lambda里写OPTIONS的处理逻辑
  • 只需要在Lambda返回业务响应的时候,统一带上Access-Control-Allow-Origin等CORS头即可
  • 优势:只需要维护一套CORS规则,OPTIONS请求的响应由APIGateway托管,不需要占用Lambda调用资源

方案2:全CDK配置,无需修改Lambda代码

如果不想在Lambda代码里处理任何HTTP头相关的逻辑,可以关闭Lambda代理集成,通过CDK配置响应映射自动注入CORS头,示例代码如下:

const api = new apiGateway.RestApi(this, "comments-api", {
  // 保留自动处理OPTIONS预检
  defaultCorsPreflightOptions: { 
    allowOrigins: apiGateway.Cors.ALL_ORIGINS,
    allowMethods: ["GET", "OPTIONS"],
    allowHeaders: ["Content-Type"]
  }
})

const comments = api.root.addResource("comments")
const comment = comments.addResource("{post_slug}")

// 配置非代理模式的Lambda集成,添加响应头映射
const getCommentIntegration = new apiGateway.LambdaIntegration(listCommentsFunction, {
  proxy: false,
  // 配置请求参数映射,按需把路径/查询参数传给Lambda
  requestTemplates: {
    "application/json": JSON.stringify({
      post_slug: "$method.request.path.post_slug"
    })
  },
  // 配置集成响应,自动注入CORS头
  integrationResponses: [{
    statusCode: "200",
    responseParameters: {
      "method.response.header.Access-Control-Allow-Origin": "'*'",
      "method.response.header.Access-Control-Allow-Methods": "'GET,OPTIONS'",
      "method.response.header.Access-Control-Allow-Headers": "'Content-Type'"
    }
  }]
})

// 给GET方法声明允许返回的CORS头
comment.addMethod("GET", getCommentIntegration, {
  requestParameters: {
    "method.request.path.post_slug": true
  },
  methodResponses: [{
    statusCode: "200",
    responseParameters: {
      "method.response.header.Access-Control-Allow-Origin": true,
      "method.response.header.Access-Control-Allow-Methods": true,
      "method.response.header.Access-Control-Allow-Headers": true
    }
  }]
})

该方案的优势是Lambda完全不需要关心HTTP层逻辑,仅处理业务即可,劣势是需要额外维护请求/响应映射规则,适配复杂请求场景的成本更高。

内容的提问来源于stack exchange,提问作者Ben Wainwright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:09:02