728x90
반응형
1. HTTP 모듈이란
http 모듈은 Node.js에서 HTTP 서버와 클라이언트를 생성하기 위한 내장 모듈입니다. 별도의 웹 프레임워크 없이도 HTTP 서버를 구축할 수 있으며, Express.js 같은 프레임워크도 내부적으로 이 모듈을 기반으로 동작합니다.
2. HTTP 서버 생성
2.1 기본 서버
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('안녕하세요, Node.js HTTP 서버입니다!');
});
server.listen(3000, () => {
console.log('서버가 http://localhost:3000 에서 실행 중입니다.');
});
2.2 요청 정보 확인
const http = require('http');
const server = http.createServer((req, res) => {
console.log('요청 메서드:', req.method);
console.log('요청 URL:', req.url);
console.log('요청 헤더:', req.headers);
console.log('User-Agent:', req.headers['user-agent']);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
method: req.method,
url: req.url
}));
});
server.listen(3000);
3. 라우팅 구현
3.1 기본 라우팅
const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
// Content-Type 설정
res.setHeader('Content-Type', 'application/json; charset=utf-8');
if (method === 'GET' && url === '/') {
res.writeHead(200);
res.end(JSON.stringify({ message: '홈페이지' }));
} else if (method === 'GET' && url === '/users') {
res.writeHead(200);
res.end(JSON.stringify({ users: ['홍길동', '김철수'] }));
} else if (method === 'POST' && url === '/users') {
res.writeHead(201);
res.end(JSON.stringify({ message: '사용자 생성됨' }));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
server.listen(3000);
3.2 URL 파라미터 처리
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;
res.setHeader('Content-Type', 'application/json');
// /users/123 형태의 URL 처리
const userMatch = pathname.match(/^\/users\/(\d+)$/);
if (userMatch) {
const userId = userMatch[1];
res.end(JSON.stringify({ userId }));
return;
}
// /search?q=keyword 형태의 쿼리 파라미터 처리
if (pathname === '/search') {
res.end(JSON.stringify({ keyword: query.q }));
return;
}
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not Found' }));
});
server.listen(3000);
4. 요청 본문 처리
4.1 POST 요청 데이터 받기
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/users') {
let body = '';
// 데이터를 청크 단위로 수신
req.on('data', (chunk) => {
body += chunk.toString();
});
// 모든 데이터 수신 완료
req.on('end', () => {
try {
const data = JSON.parse(body);
console.log('받은 데이터:', data);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
message: '사용자 생성됨',
user: data
}));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: '잘못된 JSON 형식' }));
}
});
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
4.2 프로미스로 요청 본문 처리
function getRequestBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => body += chunk.toString());
req.on('end', () => {
try {
resolve(JSON.parse(body));
} catch (err) {
reject(err);
}
});
req.on('error', reject);
});
}
const server = http.createServer(async (req, res) => {
if (req.method === 'POST') {
try {
const data = await getRequestBody(req);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: data }));
} catch (err) {
res.writeHead(400);
res.end('Bad Request');
}
}
});
반응형
5. 정적 파일 제공
const http = require('http');
const fs = require('fs');
const path = require('path');
const MIME_TYPES = {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif'
};
const server = http.createServer((req, res) => {
let filePath = path.join(__dirname, 'public', req.url);
// 기본 파일 설정
if (req.url === '/') {
filePath = path.join(__dirname, 'public', 'index.html');
}
const ext = path.extname(filePath);
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
res.writeHead(404);
res.end('File Not Found');
} else {
res.writeHead(500);
res.end('Server Error');
}
return;
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
});
});
server.listen(3000);
6. HTTP 클라이언트 요청
6.1 GET 요청
const http = require('http');
const options = {
hostname: 'jsonplaceholder.typicode.com',
path: '/posts/1',
method: 'GET'
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('응답:', JSON.parse(data));
});
});
req.on('error', (err) => {
console.error('에러:', err.message);
});
req.end();
6.2 POST 요청
const http = require('http');
const postData = JSON.stringify({
title: '새 글',
body: '내용입니다',
userId: 1
});
const options = {
hostname: 'jsonplaceholder.typicode.com',
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log('응답:', JSON.parse(data)));
});
req.write(postData);
req.end();
6.3 간단한 GET 요청 (http.get)
const http = require('http');
http.get('http://jsonplaceholder.typicode.com/posts/1', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
}).on('error', err => console.error(err));
7. HTTPS 서버
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('HTTPS 서버입니다');
});
server.listen(443, () => {
console.log('HTTPS 서버 실행 중');
});
결론
Node.js의 http 모듈은 HTTP 서버와 클라이언트를 구현하기 위한 기본 도구입니다. createServer로 서버를 생성하고, 요청 객체(req)와 응답 객체(res)를 통해 HTTP 통신을 처리합니다. 실제 프로덕션에서는 Express.js 같은 프레임워크를 사용하는 것이 일반적이지만, http 모듈의 동작 원리를 이해하면 프레임워크를 더 효과적으로 활용할 수 있습니다.
728x90
반응형
'Node.js' 카테고리의 다른 글
| Node.js의 URL 모듈(url module) (0) | 2026.02.23 |
|---|---|
| Node.js의 파일 시스템 모듈(fs module) (0) | 2026.02.23 |
| Node.js의 모듈 시스템 (0) | 2026.02.22 |
| Node.js의 async/await 사용법 (0) | 2026.02.22 |
| Node.js의 프로미스(Promise) 사용법 (0) | 2026.02.22 |