출시·고도화 중
NestJS · Express 안내서 · 1/6
이 장에서는 Node.js에서 Express로 가장 작은 웹 서버를 만들어 본 뒤, Nest CLI로 NestJS 프로젝트를 만들고 개발 서버를 실행합니다. 마지막으로 편집기 설정을 살펴봅니다.
Express는 Node.js용 웹 프레임워크로, 라우팅과 미들웨어라는 작은 핵심만 제공하고 나머지 구조는 개발자에게 맡깁니다. NestJS는 그 위에 모듈, 의존성 주입, 데코레이터 같은 구조를 얹은 서버 프레임워크입니다. Nest는 HTTP 처리를 플랫폼 어댑터에 맡기는데, 기본값이 Express(@nestjs/platform-express)입니다. 따라서 Nest 애플리케이션도 내부에서는 Express 서버로 동작하며, 필요하면 Express 미들웨어를 그대로 쓸 수 있습니다. 어댑터를 Fastify로 바꾸는 것도 가능합니다.
두 프레임워크 모두 Node.js가 필요합니다. 먼저 설치된 버전을 확인합니다. 새로 설치한다면 nodejs.org의 LTS(장기 지원) 버전을 권합니다.
node --version
npm --version빈 폴더에서 package.json을 만들고 Express를 설치합니다.
mkdir hello-express
cd hello-express
npm init -y
npm install expressindex.js 파일을 만들고 다음 코드를 넣습니다. express()가 애플리케이션 객체를 만들고, app.get이 GET 요청 하나를 처리할 함수를 등록하며, app.listen이 포트를 열어 요청을 기다립니다.
// index.js
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
});node index.js로 실행하고 브라우저에서 http://localhost:3000을 열면 "Hello World!"가 보입니다. 개발 중에는 Node.js에 들어 있는 감시 모드를 쓰면 파일을 저장할 때마다 서버가 다시 시작됩니다.
node --watch index.jsNest 프로젝트는 공식 명령줄 도구인 Nest CLI로 만드는 것이 일반적입니다. 전역으로 설치한 뒤 nest new로 새 프로젝트를 만듭니다.
npm i -g @nestjs/cli
nest new hello-nest
cd hello-nest
npm run start:devnest new는 사용할 패키지 관리자(npm, yarn, pnpm)를 묻고, TypeScript 설정과 테스트 환경이 갖춰진 프로젝트를 만든 다음 의존성을 설치합니다. 전역 설치를 원하지 않으면 npx @nestjs/cli new hello-nest로 같은 일을 할 수 있습니다. npm run start:dev는 nest start --watch를 실행하므로 소스를 고칠 때마다 다시 컴파일하고 재시작합니다. 서버가 뜨면 http://localhost:3000에서 "Hello World!"를 확인할 수 있습니다.
애플리케이션의 시작점은 src/main.ts입니다. NestFactory.create가 루트 모듈 AppModule로 애플리케이션을 만들고 포트를 엽니다.
// src/main.ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();생성된 package.json에는 자주 쓰는 스크립트가 들어 있습니다.
| 스크립트 | 하는 일 |
|---|---|
npm run start:dev | 감시 모드로 개발 서버 실행 |
npm run start:debug | 디버거를 붙일 수 있게 감시 모드로 실행 |
npm run build | TypeScript를 dist 폴더로 컴파일 |
npm run start:prod | 빌드된 dist/main.js 실행 |
npm run test · npm run test:e2e | 단위 테스트 · e2e 테스트 |
npm run lint | ESLint 검사 |
CLI의 generate 명령(줄여서 g)은 파일을 만들고 가까운 모듈에 자동으로 등록합니다.
nest generate controller hello
# 줄여서
nest g co hello만들어진 src/hello/hello.controller.ts를 다음처럼 고칩니다. 핸들러가 객체를 돌려주면 Nest가 JSON으로 바꿔 응답합니다.
import { Controller, Get, Query } from "@nestjs/common";
@Controller("hello")
export class HelloController {
@Get()
greet(@Query("name") name?: string) {
return { message: `Hello, ${name ?? "world"}!` };
}
}curl "http://localhost:3000/hello?name=Nest"
# {"message":"Hello, Nest!"}VS Code는 TypeScript를 기본으로 지원하므로 자동 완성과 타입 검사가 바로 동작합니다. Nest 프로젝트에는 ESLint와 Prettier 설정이 함께 만들어지므로 두 확장을 설치하고 저장 시 서식 맞춤을 켜 두면 좋습니다. 디버깅은 npm run start:debug로 서버를 띄운 뒤 편집기의 Node.js 디버거를 붙이면 됩니다. WebStorm 같은 다른 편집기도 같은 방식으로 쓸 수 있습니다.
npm install express와 몇 줄의 코드로 시작할 수 있습니다.npm i -g @nestjs/cli, nest new, npm run start:dev 순서로 만들고 실행합니다.nest g로 컨트롤러 같은 구성 요소를 만들면 모듈 등록까지 자동으로 처리됩니다.
댓글 0개
로그인 · 로그인하면 댓글을 남길 수 있습니다.
첫 댓글을 남겨 보세요.