app.controller.ts 소스 살펴보기

지난번엔 서버를 구동하여 "hello world"를 띄워 보았어요.

localhost의 root경로로 request가 response 되는 것을 확인한 것입니다.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

app.controller.ts를 보면 Spring 프레임워크와 굉장히 익숙한 구조임을 알 수 있어요. 서버가 수행해야 할 일을 '@' Annotation, Decorator(어노테이션, 데코레이터)로 기술합니다.

 

@Controller 데코레이터를 클래스에 선언함으로써 해당 클래스는 컨트롤러의 역할을,

@Get() 데코레이터를 가진 getHello 함수는 root경로로 들어오는 request(요청)를 처리할 수 있습니다.

 

@Controller() 데코레이터를 보면 ( )가 있다. 여기에 인자를 입력하여 라우팅 경로는 정해줄 수 있어요. 예를들어 backend에서 주로 사용하는 'app'이라고 입력하면 우리가 지난번에 테스트했던 https://localhost:3000/app으로 접근해야 "hello world"를 만날 수 있는 것이죠!

  @Get('/helloworld')
  getHello(): string {
    return this.appService.getHello();
  }

@Get() 안에는 '/'가 생략되어 루트 경로이며, '/helloworld'로 변경한다면, 기존의 http://localhost:3000/ 요청에 대하여 404 에러를 만나게 될 것이고, http://localhost:3000/helloworld로 요청해야 "hello world"페이지를 응답받을 수 있을 것이다.

좌 : helloworld로 호출      /          우 : root 호출                                           

 

소스로 보면 @Controller(에는 "prefix:", @Get(에는 "path"라고 붙여진 게 확실히 보여서 더 쉽게 이해할 수 있습니다.

728x90
반응형

'NestJS' 카테고리의 다른 글

[NestJS] swagger에서 테스트하기  (0) 2022.03.23
[NestJS] Authentication 구현  (0) 2022.03.18
[NestJS] CRUD 구현해보기  (0) 2022.03.07
[NestJS] 개발하기  (0) 2022.02.25
[NestJS] 시작하기  (0) 2022.02.25

+ Recent posts