import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(8000);
}
bootstrap();
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get() // Decorator, 함수나 class에 기능을 첨가 해주는 것, @Get() === @Get("/")
getHello(): string {
return this.appService.getHello();
}
}
private 접근 제한자
this.requestService는 오직 RequestController 내부의 메서드들에서만 사용할 수 있다.readonly 읽기 전용
this.requestService = ... 같은 재할당 구문은 컴파일 에러.private/public/protected/readonly 등과 같은 접근제어자가 있음private readonly appService: AppService;
constructor(appService: AppService) {
this.appService = AppService;
}
위 구문을 한 줄로 축약한 것
@Get()은 Decorator, 함수나 class에 기능을 첨가 해주는 역할을 한다.
@Get() === @Get("/")
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller("cats")
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('/all/:id/:name') // Decorator, 함수나 class에 기능을 첨가 해주는 것, @Get() === @Get("/")
getHello(
@Req() req: Request,
@Body() body,
@Param() param: { id: string; name: string },
): string {
console.log(param);
return this.appService.getHello();
}
}
localhost:8000/cats/all/1/blue으로 요청을 보내는 경우 요청이 위 라우터로 향한다.
express에서 req.params , req.body 으로 요청을 받는 것과는 다르게 @Body, @Param을 통해 요청을 받는다.
@Body의 경우 DTO로 받는게 일반적이다.