[Nest js] basic - Post 요청시 body값 불러오기

giyeon·2022년 3월 11일
0

nest js - basic

목록 보기
4/8


이 포스팅은 Youtube 'John Ahn'의 '따라하면서 배우는 NestJS'를 참고했습니다.

클라이언트가 board라는 게시물을 하나 생성한다고 가정해봅시다.
서버에 Post요청으로 title, description을 넘겨주게되면 서버는 그 값을 가지고 게시물(Board)를 생성합니다.

아래는 service의 createBoard method입니다.

boards.service.ts

...
  createBoard(title: string, desc: string): Board {
    const board: Board = {
      id: uuid,
      title,
      desc,
      status: BoardStatus.PUBLIC,
    };
    this.boards.push(board);
    return board;
  }
...

createBoard라는 method는 string type인 title, desc 를 받아 하나의 새로운 board를 생성해 boards array에 추가해주게 됩니다.
후에 생성한 board를 return 해줘요.

controller 부분에서 이 method를 사용하려면 client에서 넘어온 title, desc를 인자로 받아와야 해요.
클라이언트에서 보낸 title, desc는 body에 담겨져 서버에 보내집니다.

서버는 이 body값을 뜯어보고 그 안에 있는 title, desc를 찾아서 위의 method를 이용해야 해요.

클라이언트에서 보내온 Body값은 아래와같이 꺼내볼 수 있습니다.

boards.controller.ts

...
  @Post('/')
  createBoard(@Body('title') title: string, @Body('desc') desc: string): Board {
    return this.boardsService.createBoard(title, desc);
  }
...

@Body body 를 통해서 body에 담겨져 있는 모든 값들을 가져올 수 있고,

@Body('example') example 을 통해 body값중 원하는 값만 가져올 수 있어요.

Post 요청 처리 부분을 보면 인자로 클라이언트에서 넘어온 Body의 title, desc만 콕 찝어서 받아요.
그런다음 service method로 해당 값을 넘겨주게 되면 service method를 거쳐
결국 생성된 board를 클라이언트에게 return하게 됩니다. 🙋🏻‍♂️

profile
Web , App developer wannabe 🧑🏻‍💻

0개의 댓글