컨트롤러
컨트롤러를 정의하는데 필요한 @Controller( ) 데코레이터. router( ) 역할
컨트롤러는 들어오는 요청 을 처리 하고 클라이언트에 응답 을 반환 하는 역할
라우팅
@Get( ) 데코레이터 http요청 메소드 데코레이터는 nest에세 http요청(get, post, put, delete)에 대한 핸들러를 생성
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get('profile')
findAll(): string {
return 'This action returns all cats';
}
}
위 라우터는 GET요청의 /cats/profile 이다.
요청 객체
컨트롤러를 정의하는데 필요한 @Req( ) 데코레이터.
@Req( ) request: Request,
@Body( ) Body
이렇게 값을 받아올 수 있다.
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';
}
}
@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 |
상태 코드
상태 코드 는 201 인 POST 요청을 제외하고 기본적으로 항상 200
핸들러 수준에서 데코레이터를 추가하여 이 동작을 쉽게 변경할 수 있다.
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
리디렉션
응답을 특정 URL로 리디렉션하려면 @Redirect()데코레이터 또는 라이브러리별 응답 개체를 사용하고 res.redirect()직접 호출할 수 있다.
@Get()
@Redirect('https://nestjs.com', 301)
경로 매개변수
@Param( )
@Param()메서드 매개 변수를 장식하는 데 사용되며, 경로 매개 변수를 메서드 본문 내에서 장식된 메서드 매개 변수의 속성으로 사용할 수 있다.
params.id
id 참조하여 매개변수에 액세스할 수 있다.
특정 매개 변수 토큰을 데코레이터에 전달한 다음 메서드 본문에서 이름으로 경로 매개 변수를 직접 참조할 수도 있다.
@Get(':id')
findOne(@Param() params): string {
console.log(params.id);
return `This action returns a #${params.id} cat`;
}
참고)
https://docs.nestjs.com/controllers
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
'백엔드 > nest.js' 카테고리의 다른 글
[nest.js] 계층 구조 / DI / Provider (0) | 2022.11.25 |
---|---|
[nest.js] 개발환경 세팅하기 (0) | 2022.11.24 |