[Node.js 훑어보기] #5 http / https / http2

mechaniccoder·2020년 7월 23일
0

Node.js 알아가기

목록 보기
5/7
post-thumbnail

https 모듈은 웹 서버에 SSL 암호를 추가합니다. GET, POST와 같은 메소드로 데이터를 주고 받을 때 이를 암호화하여 다른 사람이 요청, 응답을 해킹하더라도 데이터를 확인할 수 없습니다. 요즘 http로 서버를 구축하면 브라우저에서 안전하지 않다는 경고문구가 뜨게 됩니다. https는 필수라고 할 수 있겠죠.

https 암호화를 적용하기 위해서는, 인증서를 인증기관에서 발급받아야 합니다. 이는 나중에 다뤄보겠습니다.

먼저 앞서 배운 http서버 구축방법을 알아보죠.

const http = require("http");

http
  .createServer((req, res) => {
    res.write("<h1>Hello, http server!</h1>");
    res.end();
  })
  .listen(8080, () => {
    console.log("8080");
  });

8080포트에 서버를 구축했습니다.

다음으로 https로 구축할 경우에는 어떻게 할까요?

const https = require("https");
const fs = require("fs");

https
  .createServer(
    {
      cert: fs.readFileSync("도메인 인증서 경로"),
      key: fs.readFileSync("도메인 비밀키 경로"),
      ca: [
        fs.readFileSync("상위 인증서 경로"),
        fs.readFileSync("상위 인증서 경로"),
      ],
    },
    (req, res) => {
      res.write("<h1>Hello! https</h1>");
      res.end();
    }
  )
  .listen(8081, () => {
    console.log("8081");
  });

첫번째 인자로 옵션을 주면 됩니다. 도메인 인증서와 상위 인증서의 경로를 읽어와야 하죠.

그 다음으로는 http2 모듈에 대해서 알아봅시다. http2 모듈은 SSL 암호화와 추가적으로 최신 HTTP프로토콜인 http/2를 사용합니다. http/2의 요청, 응답 방식은 http/1.1보다 훨씬 업그레이드 됐기 때문에 효율적이며 웹 성능도 많이 개선됐습니다.

구현방식은 https와 비슷합니다.

const http2 = require("http2");
const fs = require("fs");

http2
  .createSecureServer(
    {
      cert: fs.readFileSync("도메인 인증서 경로"),
      key: fs.readFileSync("도메인 비밀키 경로"),
      ca: [
        fs.readFileSync("상위 인증서 경로"),
        fs.readFileSync("상위 인증서 경로"),
      ],
    },
    (req, res) => {
      res.write("<h1>Hello! http2</h1>");
      res.end();
    }
  )
  .listen(8081, () => {
    console.log("8081");
  });

References


  • 조현영『Node.js 교과서』, (주)도서출판 길벗(2019년 2월 2일), p.117~ 118
profile
세계 최고 수준을 향해 달려가는 개발자입니다.

0개의 댓글