AWS API Gateway CORS - CORS 已在 API 网关和 Lambda 函数中设置

问题描述 投票:0回答:1

我已将发出接收 CORS 消息的请求的域(github.io 页面)添加到 API 网关接口的 CORS 区域,但这没有任何帮助。

enter image description here

当我从 github 页面直接调用相同的 url 到浏览器地址栏时,预期的答案通常显示:“Hello from lambda!”

enter image description here

有人吗?

amazon-web-services cors aws-api-gateway
1个回答
0
投票

在API网关中,您需要添加带有选项动词的资源和方法,并进行始终以200响应的MOCK集成我在terraform中有一段代码,我在其中为CORS配置API网关,请检查它,我希望它会有所帮助配置

   resource "aws_api_gateway_resource" "cors" {
  rest_api_id = var.rest_api_id
  parent_id   = var.rest_api_parent_id
  path_part   = "{cors+}"
}

resource "aws_api_gateway_method" "cors" {
  rest_api_id   = var.rest_api_id
  resource_id   = aws_api_gateway_resource.cors.id
  http_method   = "OPTIONS"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "cors" {
  rest_api_id = var.rest_api_id
  resource_id = aws_api_gateway_resource.cors.id
  http_method = aws_api_gateway_method.cors.http_method
  type        = "MOCK"
  request_templates = {
    "application/json" = jsonencode(
      {
        statusCode = 200
      }
    )
  }
}

resource "aws_api_gateway_method_response" "cors" {
  depends_on  = [aws_api_gateway_method.cors]
  rest_api_id = var.rest_api_id
  resource_id = aws_api_gateway_resource.cors.id
  http_method = aws_api_gateway_method.cors.http_method
  status_code = 200
  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
  }
  response_models = {
    "application/json" = "Empty"
  }
}

resource "aws_api_gateway_integration_response" "cors" {
  depends_on  = [aws_api_gateway_integration.cors, aws_api_gateway_method_response.cors]
  rest_api_id = var.rest_api_id
  resource_id = aws_api_gateway_resource.cors.id
  http_method = aws_api_gateway_method.cors.http_method
  status_code = 200
  response_parameters = {
    "method.response.header.Access-Control-Allow-Origin"  = "'*'", # replace with hostname of frontend (CloudFront)
    "method.response.header.Access-Control-Allow-Headers" = "'Content-Type'",
    "method.response.header.Access-Control-Allow-Methods" = "'GET, POST, DELETE'" # remove or add HTTP methods as needed
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.