본문 바로가기

Node.js

[Node] https와 http2

1️⃣ https 모듈

- 웹 서버에 SSL 암호화를 추가

- GET 이나 POST 요청을 할 때 오가는 데이터를 암호화해서 중간에 다른 사람이 요청을 가로채더라도 내용을 확인할 수 없게 함

- 로그인이나 결제가 필요한 창에서 https 적용이 필수

- 인증서를 인증기관에서 구입 혹은 Let's Encrypt 같은 기관에서 무료로 발급 받아야함

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

https.createServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });

- 실제 서버에서는 80포트 대신 443 포트를 사용

 

2️⃣ http2 모듈

- SSL 암호화와 더불어 최신 HTTP 프로토콜인 http/2를 사용할 수 있게 함.

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

http2.createSecureServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });

- createServer 메서드를 createSecure Server 메서드로 바꾸면 됨.

 

 

 

 


Reference

- Node.js 교과서 개정 2판

'Node.js' 카테고리의 다른 글

[Node] package.json과 node-modules  (0) 2022.12.17
[Node] cluster  (0) 2022.12.11
[Node] 쿠키와 세션  (0) 2022.12.11
[Node] REST, HTTP 메서드 개념  (0) 2022.12.11
[Node] 이벤트, 이벤트 메서드  (0) 2022.12.10