버그와 삽질
[serverless framework] lambda+API Gateway에서 CORS 허용하기
유호건
2022. 8. 16. 22:31
반응형
아래와 같은 형식으로 응답하는 lambda 함수가 있었다.
이 lambda 함수는 API Gateway v2와 연결되어 동작한다.
'use strict';
module.exports = (statusCode, body, additionalHeaders = null) => {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'type, token, uid, Content-Type',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
...additionalHeaders
};
return {
statusCode,
headers,
body: JSON.stringify(body)
}
}
분명히 헤더에 CORS를 허용하기 위한 항목들을 넣어주었음에도 불구하고
클라이언트단에서 요청시 프리플라이트가 정상적으로 반응하지 않았다.
원인은 프리플라이트 요청(OPTION)은 lambda까지 가지 않고 API Gateway단에서 처리되기 때문이었다.
따라서 API Gateway의 설정을 변경하여 OPTION 요청을 처리할 수 있도록 하여야 한다.
https://www.serverless.com/framework/docs/providers/aws/events/http-api/#cors-setup
Serverless Framework - AWS Lambda Events - HTTP API (API Gateway v2)
The Serverless Framework documentation for AWS Lambda, API Gateway, EventBridge, DynamoDB and much more.
www.serverless.com
아래와 같이 serverless.yml의 provider 블록을 수정하였다.
provider:
name: aws
runtime: nodejs16.x
region: ap-northeast-2
stage: ${opt:stage, 'dev'}
httpApi:
cors:
allowedOrigins:
- http://localhost:3000
allowedHeaders:
- Content-Type
allowedMethods:
- GET
- POST
allowCredentials: true
exposedResponseHeaders:
- Special-Response-Header
maxAge: 6000
반응형