DevOps

NestJS + AWS API Gateway 사용시 CORS 설정

꼰딩 2024. 6. 16. 23:24

NestJS

// main 파일
app.enableCors({
    origin: [process.env.CLIENT_HOST],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'],
    allowedHeaders: [
      'Content-Type',
      'Authorization',
      'X-Requested-With',
      'X-HTTP-Method-Override',
      'X-Forwarded-Proto',
      'X-Forwarded-For',
      'X-Forwarded-Port'
    ],
    optionsSuccessStatus: 204

terraform api gateway v2

resource "aws_apigatewayv2_api" "lambda" {
  name          = "mbti-lambda-gw"
  protocol_type = "HTTP"
  cors_configuration {
    allow_origins = [var.mbti_client_local_host]
    allow_headers = ["Content-Type",
      "Authorization",
      "X-Requested-With",
      "X-HTTP-Method-Override",
      "X-Forwarded-Proto",
      "X-Forwarded-For",
    "X-Forwarded-Port"]
    allow_methods     = ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"]
    max_age           = 300
    allow_credentials = true
  }
}

nestjs 설정에서 methods: '*' 로 지정하면 정상작동안합니다.
nestjs와 api gateway 모두 설정해주어야하고, 둘 중 하나라도 설정하지 않으면 cors 에러 발생합니다.

참고