nodejs-express-server은(는) 무엇을 하나요?
미들웨어, 인증, 라우팅 및 데이터베이스 통합을 통해 프로덕션 수준의 Express.js 서버를 구축합니다. REST API 생성, 요청/응답 관리, 미들웨어 체인 구현 및 서버 로직 처리 시 사용하세요.
개요
이 스킬은 Express.js 애플리케이션 개발을 위한 모범 사례와 패턴을 제공합니다. 주요 구성 요소는 다음과 같습니다:
- 미들웨어 체인: 요청 로깅, 본문 구문 분석, CORS 등 기본 미들웨어 설정.
- 인증: JWT 기반 사용자 인증 및 권한 부여.
- 라우팅: 모듈식 라우트 구성.
- 데이터베이스 통합: MongoDB 연결 및 스키마 정의.
- 오류 처리: 중앙 집중식 오류 처리 미들웨어.
설정
npm init -y
npm install express mongoose cors dotenv jsonwebtoken bcryptjs
기본 서버 예제
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
// 미들웨어
app.use(cors());
app.use(express.json());
// 데이터베이스 연결
mongoose.connect(process.env.MONGODB_URI)
.then(() => console.log('MongoDB 연결 성공'))
.catch(err => console.error('MongoDB 연결 오류:', err));
// 라우트
app.get('/api/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date().toISOString() });
});
// 서버 시작
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`서버가 포트 ${PORT}에서 실행 중입니다.`);
});
미들웨어 체인 예제
// 사용자 정의 로깅 미들웨어
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// 인증 미들웨어
const authenticate = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ message: '인증 실패: 토큰이 필요합니다.' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: '인증 실패: 유효하지 않은 토큰입니다.' });
}
};
// 보호된 라우트에 인증 미들웨어 적용
app.get('/api/profile', authenticate, (req, res) => {
res.json({ user: req.user });
});
라우팅 예제
// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');
router.get('/', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ message: '사용자 조회 중 오류 발생', error });
}
});
router.post('/register', async (req, res) => {
try {
const { name, email, password } = req.body;
const user = new User({ name, email, password });
await user.save();
res.status(201).json({ message: '사용자 생성 성공', userId: user._id });
} catch (error) {
res.status(400).json({ message: '사용자 생성 중 오류 발생', error });
}
});
module.exports = router;
// app.js - 메인 서버 파일
const userRoutes = require('./routes/users');
app.use('/api/users', userRoutes);
환경 변수
.env 파일을 생성하고 다음 변수를 설정하세요:
PORT=5000
MONGODB_URI=mongodb://localhost:27017/yourapp
JWT_SECRET=your_jwt_secret_key_change_this
NODE_ENV=development
오류 처리
// 중앙 집중식 오류 처리 미들웨어
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
message: err.message || '내부 서버 오류',
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
});
});
스킬 사용 방법
이 스킬은 다음 상황에 유용합니다:
- REST API 구축
- 요청/응답 처리
- 미들웨어 체인 구현
- 데이터베이스 통합
- 인증 및 권한 부여
- 오류 처리
- 서버 로직 관리