사고쳤어요
Node.js 기본 웹서버 만들기 본문
Node.js를 사용하여 기본 웹서버를 만들어보자.
먼저 http라는 변수에 require("http")를 정의한다.
require 함수는 Node.js에서 제공하는 모듈을 사용하겠다는 의미로, http 프로토콜을 사용하겠다는 의미이다.
후에 http.createServer()라는 함수를 통해 서버를 생성할 수 있다.
이제 createServer()안에 넣을 함수를 만들어보자.
onRequest()라는 함수를 만들고 파라미터로 request와 response 변수를 넣어준다.
onRequest() 함수 내에 들어가는 내용들은 다음과 같다.
- response.writeHead(statusCode, headers)
- statusCode : http response의 상태코드를 말한다. (정상 - 200, Not found - 404, 오류 - 500)
- headers : http response header를 나타내는 {key : value} 쌍이 담긴 객체이다.
- response.write()
- response의 body를 작성한다.
- response.end()
- 서버와 브라우저 사이의 connection을 끊는 시점을 명시한다.
마지막으로, http.createServer(onRequest).listen(8888)을 통해 포트 번호 8888에 서버를 만들 준비를 마친다.
// server.js
let http = require("http");
function onRequest(request, response) {
response.writeHead(200, { "Content-Type": "text/html" });
response.write("Hello Node.js");
response.end();
}
http.createServer(onRequest).listen(8888);
터미널에서 node server.js를 입력하고, 웹페이지에서 localhost:8888에 접속하면 웹페이지가 잘 로드되는 것을 확인할 수 있다.

'웹 풀스택' 카테고리의 다른 글
| Node.js에서 Router를 통해 url 읽어내기 (0) | 2025.02.04 |
|---|---|
| Node.js 서버 모듈화 (0) | 2025.02.04 |
| Javascript와 Javascript-HTML 연결 방법, Javascript 태그 연결 방법 (0) | 2025.02.03 |
| CSS와 CSS-HTML 연결 방법 (0) | 2025.02.03 |
| 웹의 구성 요소 (1) | 2025.01.31 |