Node.js로 웹 서버 띄우기

binary·2021년 12월 30일
1

일팔공

목록 보기
13/20
post-thumbnail

Node.js

구글 크롬의 JsvaScript 엔진 (V8 Engine)을 기반으로 만들어진 서버 사이드 플랫폼이다.
Node.js는 웹 서버가 아니라 코드를 실행할 수 있는 하나의 방법이다.

특징

  • 비동기 I/O 처리
  • 빠른 속도
  • 단일 쓰레드
  • 뛰어난 확장성
  • MIT 라이센스 적용

어디에 자주 쓸까?

  • 입출력이 잦은 앱
  • 데이터스트리밍 앱
  • 데이터를 실시간으로 다루는 앱 (예. 소켓프로그래밍)
  • JSON API 기반 앱

CPU 사용률이 높은 앱에서는 비권장.

웹 서버 띄우기

// Node.js에 내장된 라이브러리 
const http = require("http");

http.createServer(function (req, res){
  // 요청에 응답 헤더를 보내는 ‘http’ 모듈의 내장 속성
  res.writeHead(200);
  // 응답 끝내기. 함수의 return과 비슷하다.
  res.end("Hello World!");
}).listen(3000, function() {
  console.log("Server on : 3000 port");
})

createServer() 는 첫번째 인자로 콜백함수를 받는다.
req 는 요청 객체 (리퀘스트) 이고,
res 는 응답 객체 (리스폰스) 이다.
listen() 은 특정 포트를 여는 함수 이다.

주소 창에 localhost:3000 을 입력하면 확인할 수 있다.

const http = require("http");

http.createServer((req, res) => {
  let url = req.url;
  let method = req.method;
  let headers = req.headers;

  console.log(url);
  console.log(method);
  console.log(headers);

  res.writeHead(200);
  // 한글은 인코딩,,이 필요함
  res.end("hello");
}).listen(3000, () => {
  console.log("server on : 3000 port");
});

res.end의 문자열이 한글일 경우 따로 인코딩이 필요하다.

server on : 3000 port
/ <- url
GET <- method
{
host: 'localhost:3000',
connection: 'keep-alive',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
'sec-ch-ua-mobile': '?0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'sec-ch-ua-platform': '"macOS"',
accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/,/*;q=0.8',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'no-cors',
'sec-fetch-dest': 'image',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7'
}
<- header

0개의 댓글