Research/Nest.js
nestjs_CORS 허용하기
RIEM
2023. 4. 5. 23:59
728x90
아키텍처가 프론트 리액트 페이지 - 백엔드 nest.js 이렇게 구분되어있는 시나리오다. 프론트에서 API 요청 시 axios로 post요청을 한다. 이때 CORS 문제가 종종 발생하는데, 이를 해결하는 방법을 알아보자.
공식문서에 따르면 CORS는 Cross-origin resource sharing의 약자로 다른 도메인에서 리소스를 요청할 때 이를 허용해주는 메커니즘을 말한다. https://docs.nestjs.com/security/cors
// main.ts
...
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new HttpExceptionFilter());
...
// * CORS 셋업
app.enableCors({
origin: true, // true 시 모든 url에 개방(개발 환경). 특정 url만 허용할 수 있음(배포 환경)
credentials: true, // 프론트에서 credentials 설정을 true 해주었기 때문
});
const PORT = process.env.PORT;
await app.listen(PORT);
}
bootstrap();
728x90