sudo npm i -g @nestjs/cli
nest new
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
main.ts: 시작점
app.module.ts: 루트 모듈
app.controller.ts : url을 가져오고, 함수를 실행(express의 라우터 같은 존재)
app.service.ts:
@Controller()
export class AppController {
@Get('/hello')
sayhello(): string {
return "hello everyone"
}
}
nestjs가 모든 기능을 지원해주기 때문에 router를 설정할 필요없이 url을통해 함수만 실행시켜주면됨!
post, put 등 데코레이터를 이용해 다양한 통신이 가능함
만약 @post를 사용해 잘못된 통신을 설정했다고해도 nestjs가 알아서 에러처리를 해줌
에러처리
import { Controller, Get, Post } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('/hello')
sayhello(): string {
return "hello everyone"
}
}
app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello Nest!';
}
getHi(): string {
return 'Hi Nest!'
}
}
app.controller.ts
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
@Get('/hello')
sayhello(): string {
return this.appService.getHi()
}
}