๐ ๊ณต์๋ฌธ์๋ฅผ ์ฐธ๊ณ ํ์ฌ Controller ์ ๋ฆฌํ๊ธฐ(1)
์ปจํธ๋กค๋ฌ๋ ๋ค์ด์ค๋ ์์ฒญ์ ์ฒ๋ฆฌํ๊ณ ํด๋ผ์ด์ธํธ์ ์๋ต์ ๋ฐํํ๋ ์ญํ ์ด๋ค.
์ปจํธ๋กค๋ฌ์ ๋ชฉ์ ์ ์ ํ๋ฆฌ์ผ์ด์ ์ ๋ํ ํน์ ์์ฒญ์ ์์ ํ๋ ๊ฒ์ด๋ฉฐ ๋ผ์ดํ ๋ฉ์ปค๋์ฆ์ ์ด๋ค ์ปจํธ๋กค๋ฌ๊ฐ ์ด๋ค ์์ฒญ์ ์์ ํ ์ง ์ ์ดํ๋ค. ๊ฐ ์ปจํธ๋กค๋ฌ์๋ ๋ ์ด์์ ๊ฒฝ๋ก๊ฐ ์๋ ๊ฒฝ์ฐ๊ฐ ๋ง์ผ๋ฉฐ, ๊ฒฝ๋ก๋ง๋ค ๋ค๋ฅธ ์์ ์ ์ํํ ์ ์๋ค.
๊ธฐ๋ณธ ์ปจํธ๋กค๋ฌ๋ฅผ ์์ฑํ๊ธฐ ์ํด ํด๋์ค์ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ๋ค. ๋ฐ์ฝ๋ ์ดํฐ๋ ํด๋์ค๋ฅผ ํ์ ๋ฉํ๋ฐ์ดํฐ์ ์ฐ๊ฒฐํ๊ณ Nest๊ฐ ๋ผ์ฐํ ๋งต์ ์์ฑํ ์ ์๋๋ก ํ๋ค. (์์ฒญ์ ํด๋น ์ปจํธ๋กค๋ฌ์ ์ฐ๊ฒฐ)
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
CLI๋ฅผ ์ฌ์ฉํ์ฌ ์ปจํธ๋กค๋ฌ๋ฅผ ์์ฑํ๋ ค๋ฉด ์๋ ๋ช ๋ น์ด๋ฅผ ์คํํ๋ฉด ๋๋ค.
yarn g controller cats
import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
}
์ผ๋ฐ์ ์ผ๋ก๋ NestJS์์ ์ ๊ณตํ๋ @Body(), @Query() ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํ๋ฉด ๋์ง๋ง ์๋์ ๊ฐ์ Decorator๋ค์ ์์ ๋กญ๊ฒ ์ฌ์ฉํ ์ ์์ต๋๋ค.
๋ฐ์ฝ๋ ์ดํฐ | ์ฌ์ฉ |
---|---|
@Request(), @Req() | req |
@Response(), @Res()* | res |
@Next() | next |
@Session() | req.session |
@Param(key?: string) | req.params / req.params[key] |
@Body(key?: string) | req.body / req.body[key] |
@Query(key?: string) | req.query / req.query[key] |
@Headers(name?: string) | req.headers / req.headers[name] |
@Ip() | req.ip |
@HostParam() | req.hosts |
์ฌ๊ธฐ๋ฅผ ์ฐธ๊ณ ํ๋ฉด ์ปค์คํ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ๋ง๋ค ์ ์๋ค.
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
@Post()
@Header('Cache-Control', 'none')
create() {
return 'This action adds a new cat';
}