728x90

main.ts에 enableCors()를 추가한다.

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './commons/graphql/filter/http-exption.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter());
  await app.listen(3000);
}
bootstrap();

 

cors에 기능을 추가하고 싶다면 {}안에 필요한 내용을 입력한다.

 

ex) 주소제한, 

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './commons/graphql/filter/http-exption.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://169.254.152.198:5500',
  });
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter());
  await app.listen(3000);
}
bootstrap();

 

cors 옵션은 한글로 번역해두신 글이 있어서 가져왔다.

export interface CorsOptions {
    /**
     * Configures the `Access-Control-Allow-Origins` CORS header. 
     See [here for more detail.](https://github.com/expressjs/cors#configuration-options)
    어떤 오리진과 연결을 허용할 것인가? 기본값 true or "*" */
    // type StaticOrigin = boolean | string | RegExp | (string | RegExp)[]
    // type CustomOrigin = (requestOrigin: string, callback: (err: Error | null, origin?: StaticOrigin) => void) => void
    origin?: StaticOrigin | CustomOrigin;
    /**
     * Configures the Access-Control-Allow-Methods CORS header.
     어떤 메소드의 연결을 허용할 것인가?*/
    methods?: string | string[];
    /**
     * Configures the Access-Control-Allow-Headers CORS header.
     어떤 헤더를 보낼 수 있도록 할 것인가?*/
    allowedHeaders?: string | string[];
    /**
     * Configures the Access-Control-Expose-Headers CORS header.
     브라우저에서 어떤 해더를 노출할 것인가?*/
    exposedHeaders?: string | string[];
    /**
     * Configures the Access-Control-Allow-Credentials CORS header.
     쿠키, 인증 헤더 등을 사용할 수 있게 할 것인가?*/
    credentials?: boolean;
    /**
     * Configures the Access-Control-Max-Age CORS header.
     CORS 프리플라이트 요청 결과를 캐싱할 시간을 몇으로 설정할 것인가?*/
    maxAge?: number;
    /**
     * Whether to pass the CORS preflight response to the next handler.
     CORS 프리플라이트 요청에 대한 응답이 다음 미들웨어로 전달되도록 할 것인가? 기본값 false*/
    preflightContinue?: boolean;
    /**
     * Provides a status code to use for successful OPTIONS requests.
     성공적인 OPTIONS 요청에 대한 응답 상태 코드를 어떤것을 보낼 것인가? 기본값 204*/
    optionsSuccessStatus?: number;
}

https://velog.io/@kwontae1313/NestJS-CORS

 

NestJS CORS

😀필자는 백엔드 서버를 만들기 때문에 프론트엔드와 도메인의 오리진이 다르다. 따라서 서로 리소스를 주고받기위해서 반드시 CORS설정을 해줘야 한다.NestJS에서는 CORS(Cross-Origin Resource Sharing)

velog.io

 

728x90

'코딩 > Nest.js' 카테고리의 다른 글

Swagger  (0) 2024.04.24
GlobalFilters  (0) 2024.04.22
오류 상태 코드  (0) 2024.04.20
CLI  (0) 2024.04.12
Nest.js 기본 파일 구성  (0) 2024.03.16

+ Recent posts