Node.js 인터뷰 질문 12
질문: HTTP 모듈을 사용하여 Node.js에서 간단한 서버를 생성하는 방법은 무엇인가요?
답변:
Node.js에서 HTTP 모듈을 사용하여 간단한 웹 서버를 생성하는 방법은 다음과 같습니다. 내장된 http
모듈을 사용하면 몇 줄의 코드만으로도 기본적인 웹 서버를 구현할 수 있습니다.
기본 HTTP 서버 생성하기
// 1. http 모듈 가져오기
const http = require("http");
// 2. 서버 포트 설정
const PORT = 3000;
// 3. 서버 생성
const server = http.createServer((req, res) => {
// 요청에 대한 응답 헤더 설정
res.writeHead(200, { "Content-Type": "text/plain" });
// 응답 본문 전송 및 응답 종료
res.end("Hello, World!\n");
});
// 4. 서버 시작: 지정된 포트에서 연결 대기
server.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT}/ 에서 실행 중입니다.`);
});
기본 라우팅 구현하기
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
// URL과 HTTP 메서드로 라우팅 처리
const { url, method } = req;
// 응답 헤더 기본 설정
res.setHeader("Content-Type", "text/plain");
// 라우팅 로직
if (url === "/") {
// 홈페이지
res.statusCode = 200;
res.end("홈페이지에 오신 것을 환영합니다!");
} else if (url === "/about" && method === "GET") {
// 소개 페이지
res.statusCode = 200;
res.end("이것은 소개 페이지입니다.");
} else if (url === "/api/users" && method === "GET") {
// JSON API 응답
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
const users = [
{ id: 1, name: "홍길동" },
{ id: 2, name: "김철수" },
];
res.end(JSON.stringify(users));
} else {
// 404 Not Found
res.statusCode = 404;
res.end("페이지를 찾을 수 없습니다.");
}
});
server.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT}/ 에서 실행 중입니다.`);
});
HTTP 요청 본문 처리하기
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/api/data") {
let body = "";
// 데이터 청크를 받을 때마다 호출됨
req.on("data", (chunk) => {
body += chunk.toString();
});
// 모든 데이터를 받은 후 호출됨
req.on("end", () => {
try {
const data = JSON.parse(body);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
message: "데이터가 성공적으로 수신되었습니다",
data: data,
})
);
} catch (error) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
error: "잘못된 JSON 형식입니다",
})
);
}
});
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("페이지를 찾을 수 없습니다.");
}
});
server.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT}/ 에서 실행 중입니다.`);
});
정적 파일 서빙하기
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = 3000;
const server = http.createServer((req, res) => {
// index.html 파일 제공
if (req.url === "/" || req.url === "/index.html") {
const filePath = path.join(__dirname, "public", "index.html");
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end("서버 오류");
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(content);
});
}
// 404 처리
else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
server.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT}/ 에서 실행 중입니다.`);
});
오류 처리
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
// 요청 처리 로직
if (req.url === "/error") {
// 의도적으로 오류 발생
throw new Error("테스트 오류");
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("정상 응답입니다.");
} catch (error) {
console.error("서버 오류:", error);
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("서버에 오류가 발생했습니다.");
}
});
// 서버 자체의 오류 처리
server.on("error", (error) => {
console.error("서버 시작 오류:", error);
});
server.listen(PORT, () => {
console.log(`서버가 http://localhost:${PORT}/ 에서 실행 중입니다.`);
});
이처럼 Node.js의 내장 HTTP 모듈을 사용하면 별도의 외부 프레임워크 없이도 간단한 웹 서버를 구현할 수 있습니다. 그러나 실제 프로덕션 환경에서는 Express.js와 같은 웹 프레임워크를 사용하여 라우팅, 미들웨어, 요청 처리 등을 더 쉽게 구현하는 것이 일반적입니다.