Node.js Express로 쉽게 서버 구축하기
기본 서버 설정
Setting Up the Basic Server
Node.js와 Express는 웹 애플리케이션 및 API 개발에 필요한 강력한 도구입니다. 이 장에서는 기본적인 Express 서버를 설정하고 TypeScript를 사용하여 작성하는 과정을 단계별로 살펴볼 것입니다.
Node.js 프로젝트 초기화
Express를 사용하기 위한 첫 단계는 Node.js 프로젝트를 초기화하는 것입니다. 아래 명령어로 프로젝트를 생성하고 초기화할 수 있습니다:
mkdir express-ts-server
cd express-ts-server
npm init -y
npm init -y
명령어는 기본값으로 package.json
파일을 생성합니다.
TypeScript 설치 및 설정
이제 TypeScript를 설치하고 설정하겠습니다. 아래 명령으로 TypeScript와 관련된 패키지를 설치합니다:
npm install typescript ts-node @types/node --save-dev
그런 다음 TypeScript 설정 파일 (tsconfig.json
)을 생성합니다. 아래 명령을 실행하세요:
tsconfig.json
파일 내용 예시는 다음과 같습니다:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "dist",
"rootDir": "src",
"strict": true
}
}
Express 설치
다음으로, Express를 설치합니다:
npm install express
npm install @types/express --save-dev
이제 Express가 설치되었으니 기본 서버를 만들어 봅시다.
간단한 Express 서버 작성
src/server.ts
파일을 생성하고 아래 예제를 추가하세요:
import express from 'express';
const app = express();
// 기본 라우트
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 서버 시작
const PORT = 3000;
app.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT} 에서 실행 중입니다.`);
});
이제 아래 명령을 실행하여 서버를 시작하세요:
npx ts-node src/server.ts
브라우저에서 http://localhost:3000 을 방문하면 "Hello, World!" 메시지가 표시됩니다.
결론
지금까지 Node.js 및 Express를 사용하여 TypeScript로 간단한 웹 서버를 구축하는 방법을 배웠습니다. 다음 장에서는 더 복잡한 라우팅과 API 기능을 추가하여 서버를 확장해 보겠습니다.