본문 바로가기

개발/typescript

[NestJs] Params, Query, Body

반응형

controller를 통해 요청을 받으면, client에서 올린 데이터를 약속된 방식에 따라 정리? 해야한다.

아래는 각 케이스별 컨트롤러에서의 코드이다.

 

import { Body, Controller, Post, Get, Query, Param } from "@nestjs/common";

import { userMookService, UserMockInterface } from "user/user.service";
import { UserDTO } from "user/dto/user.dto";

@Controller("user")
export class UserController {
  // state 설정을 해줘야, constructor 안에서 사용 가능
  private service: userMookService;

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

  @Get("/find-user")
  findUser(@Query() params: any): UserMockInterface[] {
    return this.service.findUsersByName(params.name);
  }

  @Get("/find-user-by-id/:id")
  findUserById(@Param() params: any): UserMockInterface {
    return this.service.findUserById(params.id);
  }

  @Post("/post")
  async addUser(@Body() user: UserDTO) {
    return user;
  }
}

 

(1) /find-user

-get 타입으로 url 끝부분에 ?와 &를 이용해 전송한다. ex: /path?name=123

-숫자로 보내도, 문자열로 올려진다

 

(2) /find-user-by-id:id

-get 타입으로 /path/:id와 같이 url 끝부분에 param을 붙인다. ex: /path/id

-숫자로 보내도, 문자열로 올려진다

 

(3) /post

-post 타입으로 body에 데이터를 담는다

-보낸 유형(객체, 배열, 숫자, 문자)로 올려진다

 

 

이상입니다.

 

 

*코드가 깨지면 아래 참조해주세요

https://medium.com/%EB%8F%84%EA%B9%A8%EB%B9%84-%EC%9D%B4%EC%95%BC%EA%B8%B0/nestjs-params-query-body-8a0997fa93d9