1. main


import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(8000);
}

bootstrap();

2. controller


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

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

  @Get() // Decorator, 함수나 class에 기능을 첨가 해주는 것, @Get() === @Get("/")
  getHello(): string {
    return this.appService.getHello();
  }
}

private readonly appService: AppService;
constructor(appService: AppService) {
  this.appService = AppService;
}

위 구문을 한 줄로 축약한 것

@Get()은 Decorator, 함수나 class에 기능을 첨가 해주는 역할을 한다.

@Get() === @Get("/")

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

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

  @Get('/all/:id/:name') // Decorator, 함수나 class에 기능을 첨가 해주는 것, @Get() === @Get("/")
  getHello(
    @Req() req: Request,
    @Body() body,
    @Param() param: { id: string; name: string },
  ): string {
    console.log(param);
    return this.appService.getHello();
  }
}

localhost:8000/cats/all/1/blue으로 요청을 보내는 경우 요청이 위 라우터로 향한다.

express에서 req.params , req.body 으로 요청을 받는 것과는 다르게 @Body, @Param을 통해 요청을 받는다.

@Body의 경우 DTO로 받는게 일반적이다.