728x90
반응형
1. http 모듈
Node.js의 http 모듈은 웹 서버를 만들 수 있게 해주는 핵심 내장 모듈로, 클라이언트(브라우저 등)의 요청(request)을 받고, 응답(response)을 반환하는 기능을 제공합니다. 이 모듈을 통해 별도의 웹 서버 소프트웨어(Apache, Nginx 등) 없이도 Node.js 자체로 웹 서버를 만들 수 있으며, http.createServer() 메서드를 사용해 요청 처리 함수를 정의하고, 서버를 특정 포트에서 실행할 수 있습니다. 주로 REST API를 만들거나 HTML 파일을 전송하는 등의 기본적인 웹 애플리케이션 서버 개발에 많이 사용됩니다.
const http = require("http");
const server = http.createServer((req, res) => {
// req: 요청 정보 (url, method, headers 등)
// res: 응답 처리 객체
});
server.listen(3000);
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, World!\n");
});
server.listen(3000, () => {
console.log("서버 실행 중 → http://localhost:3000");
});
const http = require("http");
const server = http.createServer((req, res) => {
const url = req.url;
if (url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("홈페이지입니다.");
} else if (url === "/about") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("소개 페이지입니다.");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("페이지를 찾을 수 없습니다.");
}
});
server.listen(3000, () => {
console.log("서버 실행 중 → http://localhost:3000");
});
2. html 파일 응답
📁 index.html
<!DOCTYPE html>
<html>
<head><title>홈페이지</title></head>
<body><h1>환영합니다!</h1></body>
</html>
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
if (req.url === "/") {
fs.readFile("index.html", (err, data) => {
if (err) {
res.writeHead(500);
return res.end("파일 읽기 오류");
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(3000, () => {
console.log("서버 실행 중 → http://localhost:3000");
});
3. JSON 데이터 응답
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/api/user") {
const user = {
name: "김사과",
age: 20,
job: "개발자"
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(user));
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(3000, () => {
console.log("서버 실행 중 → http://localhost:3000");
});
4. nodemon
nodemon은 Node.js 개발 시 자주 사용하는 유틸리티로, 소스 코드가 변경될 때마다 자동으로 서버를 재시작해주는 도구입니다. 일반적으로 Node.js로 서버를 실행하면 코드 수정 후 서버를 수동으로 종료하고 다시 실행해야 하는 번거로움이 있는데, nodemon을 사용하면 파일이 수정될 때마다 자동으로 서버를 재시작해줘서 개발 속도가 훨씬 빨라집니다. 설치는 npm install -g nodemon으로 전역 설치하거나 npm install --save-dev nodemon으로 프로젝트에 설치할 수 있으며, 실행은 node app.js 대신 nodemon app.js처럼 사용하면 됩니다.
전역 설치 (모든 프로젝트에서 사용 가능)
npm install -g nodemon
로컬 설치 (해당 프로젝트에서만 사용): 이 방식은 package.json에 개발 도구로 등록되므로 협업 시 유용합니다.
npm install --save-dev nodemon
package.json에 스크립트 등록
{
"name": "myapp",
"version": "1.0.0",
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
},
"devDependencies": {
"nodemon": "^3.0.0"
}
}
실행
npm run dev
728x90
반응형