클라이언트 요청을 처리하고 응답을 반환해주는 클래스로
@Controller()
데코레이터로 정의된다.
@Controller('cats') export class CatsController { @Get() findAll(): string { return 'This action returns all cats'; } }
데코레이터는 컨트롤러에 의해 처리되는 경로를 받는다.
즉, 위에 코드를 예시로 'cats' 경로로 요청이 왔을 경우 아래CatsController
클래스를 수행할 수 있다.
@Controller('cats') export class CatsController { @Get() findAll(): string { return 'This action returns all cats'; } }
@GET()
,@Post()
,@Patch()
,@Delete()
와 같은 표준 HTTP 메서드에 대한 데코레이터이다.
즉, GET 메소드로 요청을 받아 findAll 함수를 수행한다.
NestJS CLI를 사용하여 컨트롤러를 생성할 수 있다.
nest g controller boards --no-spec
- nest : nest CLI 사용
- g : generage
- controller : 생성할 틀
- boards : 이름
- --no-spec : 테스트 코드 생성 X
@Post() createCat( @Body('name') name: string, @Body('age') age: number, ) { return this.catsService.createCat(name, age); }
위 처럼 컨트롤러에서 서비스에 있는 함수를 호출할 때에는 핸들러 밑에 함수로 작성하며 사용자 보낸 데이터는
@Body() body
를 사용해 받는다.
express 에서는app.post('/', (req, res) => {console.log(req.body)})
로 사용한다.
body로 보내는 것이 아니라 URL Query로 보내는 경우에는
@Body()
대신@Param()
를 사용해 데이터를 받을 수 있다.