在AWS中使用Terraform创建s3存储桶和CloudFront分发,以及一个API网关。当在前端网页上通过API网关访问存储桶中的对象时,会遇到跨域问题。
解决此问题的方法是在API网关中添加CORS配置:
resource "aws_api_gateway_rest_api" "example" { name = "example" }
resource "aws_api_gateway_resource" "example" { rest_api_id = aws_api_gateway_rest_api.example.id parent_id = aws_api_gateway_rest_api.example.root_resource_id path_part = "example" }
resource "aws_api_gateway_method" "get" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = "GET" authorization = "NONE" }
resource "aws_api_gateway_integration" "example" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.get.http_method
type = "AWS_PROXY"
integration_http_method = "GET" uri = "arn:aws:apigateway:${var.region}:s3:path/${var.bucket}/${var.path}" }
resource "aws_api_gateway_method_response" "example" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.get.http_method status_code = "200"
response_parameters = { "method.response.header.Access-Control-Allow-Origin" = true } }
resource "aws_api_gateway_integration_response" "example" { rest_api_id = aws_api_gateway_rest_api.example.id resource_id = aws_api_gateway_resource.example.id http_method = aws_api_gateway_method.get.http_method status_code = "200"
response_templates = { "application/json" = "" }
response_parameters = { "method.response.header.Access-Control-Allow-Origin" = "'*'" } }
resource "aws_api_gateway_deployment" "example" { depends_on = [aws_api_gateway_integration_response.example] rest_api_id = aws_api_gateway_rest_api.example.id stage_name = "dev" }
此代码示例中,通过AWS API网关和S3集成,从而可以解决跨域问题。对于需要访问存储桶中数据的前端应用,可以通过此方式轻松实现。
上一篇:AWS中的TCP/IP通信
下一篇:AWS中的替代cron