Backend/Node.js
HTTP
AIHYEONJI
2025. 4. 27. 12:03
1. http 모듈
: node.js의 http 모듈은 웹 서버를 만들 수 있게 해주는 핵심 내장 모듈로 클라이언트(브라우저 등)의 요청을 받고 , 응답을 반환하는 기능을 제공함. 이 모듈을 통해 별도의 웹 서버 소프트웨어(Apache, Nginx 등) 없이도 Node.js 자체로 웹 서버를 만들 수 있으며, http.createServer() 메서드를 사용해 요청 처리 함수를 정의하고, 서버를 특정 포트에서 실행할 수 있다. 주로 REST API를 만들거나 HTML 파일을 전송하는 등의 기본적인 웹 애플리케이션 서버 개발에 많이 사용된다.
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("Home_page");
} else if (url === "/about") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Introduce_Page");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Cant find page");
}
});
// 헤더에 적을 데이터 --> 브라우저에 보내줌
// 400 이상은 page 오류
// 200~ 정상 호출
// res.writeHead(200, { "Content-Type": "text/plain" });
// res.end("Hello, World!\n");
// });
// 127.0.0.1, localhost
server.listen(3000, () => {
console.log("서버 실행 중");
});
// localhost:3000
2. html 파일 응답
📁 index.html
const http = require("http");
const fs = require("fs");
const server = http.createServer((req, res) => {
if (req.url === "/") {
fs.readFile("test.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(4000, () => {
console.log("서버 실행 중");
});
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("서버 실행 중")
})
4. nodemon
nodemon은 Node.js 개발 시 자주 사용하는 유틸리티로, 소스 코드가 변경될 떄마다 자동으로 서버를 재시작해주는 도구이다. 일반적으로 Node.js 로 서버를 실행하면 코드 수정 후 서버를 수동으로 종료하고 다시 실행해야 하는 번거로움이 있다. nodemon을 사용하면 파일이 수정될 때마다 자동으로 서버를 재사지가해줘서 개발 속도가 빨라진다.