본문 바로가기
Node

http모듈 개념 & 3000서버 만들어보기

by jennyiscoding 2022. 10. 22.

노드는 내장서버가 있기때문에 서버프로그램이 따로 필요하지 않는데, http모듈이 바로 그 역할이다.

http모듈 : http웹 서버를 생성하는 것과 관련된 모든 기능을 담당한다. 

4가지 기능을 알아보자. 

1.  createServer() : server객체를 생성
2.  writeHead() : 응답 header를 구성(어떤식으로 응답을 할것인지 정하는 역할)

          ex) resp.writeHead(200,{'content-type' : 'text/html'})의미 : 응답에 대한 헤드를 써줌. 200번일때 응답을 {'content-type' : 'text/html'}이걸로 할꺼야. 성공했을 때의 헤드는 200이야. 형태는 html이야. 그때 바디는 아래 html내용을 써서 응답할꺼야.라는 의미임.

3. end() : 응답 body를 작성
4.  listen() : 서버를 실행하고 클라이언트를 기다림 (서버를 동작시키는 함수) 

 

basic form

var http = require("http");

http
  .createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("hello world");
  })
  .listen(8080);

 

코드 : 

require 기능으로 http모듈을 불러온다. 

http.createServer를 이용해 서버를 만들어보겠다. 

http.createServer((req,resp)=> { ... 부분에서 요청은 req에 담기고 응답할 수 있는 객체는 resp에 담긴다. 

//req : 사용자 요청에 대한 정보
//resp : 사용자에게 응답을 하기 위한 정보

const http = require('http');
const server = http.createServer((req,resp)=>{
resp.writeHead(200,{'content-type' : 'text/html'});

    resp.end(`<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>http 모듈 테스트</title>
    </head>
    <body>
        <h2>http 모듈 테스트</h2>
        <p>처음으로 실행하는 node.js http서버</p>
    </body>
    </html>`);
})
//내부에 서버 하나 만드는 것이다.
//서버는 역할이 성공(200)일 때 html코드를 응답해주는게 역할이다.
server.listen(3000,()=>{
    console.log(`3000번 포트로 서버 실행중...`);
})
// 3000번 국도를 타라.
// 오른쪽에는 3000번 포트로 서버를 실행시켰을 때 호출할 함수를 쓴다.
//()안에 클라이언트가 요청을 보냈을 때 보내줄 것을 안에다 적는다.
// http://localhost:3000/ 우리가 작성한 페이지가 나온다 !

이제 크롬에 들어와서 localhost:3000 치면 처음으로 실행하는 node.js http서버라는 글자가 뜬다! 

 

두번째 예제.

이번에는 fs기능으로 html을 읽어와서 에러는 404, 에러가 아니면 200으로 localhost:3000으로 보여주는 기능을 구현해보겠다. 

var http = require('http');
var fs = require('fs');

function onRequest(request, response) {

  fs.readFile('./index.html', 'utf-8', (err, data) => {
    if (err) {
      response.writeHead(404);
      response.end(data);
    } else {
      response.writeHead(200, { 'Content-Type': 'text/html' });
      response.end(data);
    }
  });
}

http.createServer(onRequest).listen(8080);
 
test.html은 아래와 같다. 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>http 모듈 테스트</title>
</head>
<body>
    <h2>http 모듈 테스트</h2>
    <p>처음으로 실행하는 node.js http서버</p>
</body>
</html>

이렇게 뜬다. 

index.html을 index.js에서 읽는 또 다른 예제

index.js

const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer();

const publicPath = path.resolve(__dirname, "../public");

const fsp = fs.promises;

// string ver.
server.on("request", async (req, res) => {
  const { method, url } = req;

  if (method === "GET" && url === "/") {
    const indexFileString = await fsp.readFile(
      path.join(publicPath, "index.html"),
      {
        encoding: "utf-8",
      }
    );
    res.setHeader("Content-Type", "text/html");
    res.statusCode = 200;
    res.write(indexFileString);
    res.end();
    return;
  }

  res.setHeader("Content-Type", "text/html");
  res.statusCode = 404;
  res.end();
});

// stream ver.
// server.on("request", (req, res) => {
//   const { method, url } = req;

//   if (method === "GET" && url === "/") {
//     res.setHeader("Content-Type", "text/html");
//     res.statusCode = 200;
//     fs.createReadStream(path.join(publicPath, "index.html")).pipe(res);
//     return;
//   }
//   res.setHeader("Content-Type", "text/html");
//   res.statusCode = 404;
//   res.end();
// });

server.listen(3000, () => {
  console.log("웹 서버가 포트 3000에서 운영중입니다 🚀");
});

 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello World</title>
  </head>
  <body>
    <h3>Hello, World</h3>
    <p>
      Welcome to the world of Web Development! This is an example of
      <strong>web server</strong>
      using Node.js built-in libraries.
    </p>
  </body>
</html>

 

 


MIME에 대한 개념을 알아보자. 
응답의 형식이 무엇인지를 Header에 포함된 MIME을 통해 브라우저에 알려준다. 
브라우저는 이것을 참고하여 응답을 어떻게 해석할지 알수 있다. 너 이거 html로 해석해야돼~ 를 알려주는것. 

resp.writeHead(200,{'content-type':'text/html'});

이 text/html 부분에는 아래처럼 다양한 종류가 있다. 
        text/plain 일반적인 text파일
        text/html html형식 파일 
        text/css css형식
        text/xml xml 형식
        image/jpeg jpeg이미지 파일 
        image/png png이미지 파일
        video/mpeg mpeg 동영상 파일
        audio/mp3 음악 파일 
        ...

 

node.js로 만든 웹서버

var http = require('http');

function onRequest(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  res.write('Hello World');
  res.end();
}

http.createServer(onRequest).listen(8080);