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

Terraform配置API Gateway CORS失败:Output passthrough设置异常

解决Terraform配置API Gateway REST API CORS时Output Passthrough默认设为Yes的问题

核心问题在于Terraform默认会将API Gateway方法响应的Output passthrough设为Yes,而手动配置时设为No才能让CORS正常生效。要解决这个问题,只需在Terraform配置中显式指定content_handling参数即可。

直接配置API Gateway资源的解决方法

在你的aws_api_gateway_method_response资源中,添加content_handling = "CONVERT_TO_TEXT",这会对应将Output passthrough设置为No。示例配置如下:

resource "aws_api_gateway_method_response" "cors_options_200" {
  rest_api_id = aws_api_gateway_rest_api.your_api.id
  resource_id = aws_api_gateway_resource.your_resource.id
  http_method = aws_api_gateway_method.cors_options.http_method
  status_code = "200"

  # 关键配置:将Output passthrough设为No
  content_handling = "CONVERT_TO_TEXT"

  response_parameters = {
    "method.response.header.Access-Control-Allow-Origin" = true
    "method.response.header.Access-Control-Allow-Methods" = true
    "method.response.header.Access-Control-Allow-Headers" = true
  }
}

使用第三方CORS模块的解决方法

如果你用的是第三方CORS模块(比如terraform-aws-modules的api-gateway CORS模块),需要在模块参数中指定对应的content_handling配置。示例如下:

module "api_gateway_cors" {
  source  = "terraform-aws-modules/api-gateway/aws//modules/cors"
  version = "~> 1.0"

  rest_api_id = aws_api_gateway_rest_api.your_api.id
  resource_id = aws_api_gateway_resource.your_resource.id

  # 显式设置content_handling,对应Output passthrough为No
  method_response_content_handling = "CONVERT_TO_TEXT"

  allowed_origin      = "*"
  allowed_methods     = ["GET", "POST", "OPTIONS"]
  allowed_headers     = ["Content-Type", "Authorization"]
}

补充说明

API Gateway中,Output passthrough的Yes对应content_handling为CONVERT_TO_BINARY或不设置(默认值),No则对应CONVERT_TO_TEXT。即使你的Lambda代理集成能正常返回CORS头,若Output passthrough为Yes,API Gateway可能会错误处理响应头,导致CORS失效,所以必须显式配置该参数。

内容的提问来源于stack exchange,提问作者Hyden Polikoff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:09:28