Node.js

Jung taeWoong·2021년 12월 18일
0

node.js

목록 보기
1/2
post-thumbnail

Node란?

  • 자바스크립트 런타임 환경
  • 자바스크립트가 구동되는 환경을 의미하는 것이지 서버가 아니다
  • 아래 코드와 같이 http 모듈을 이용하여 서버역할을 제공하는 것일뿐
const http = require('http');
// req: 요청에 대한 정보
// res: 응답에 대한 정보
const server = http.client((req, res) => {
  console.log(req.url, res.method);
  res.end('Hello world'); // end는 마지막 1번만 사용
});
server.listen(3000, () => {
  console.log('Server running on port 3000');
});

Front Server(SSR)와 Back Server(API)를 나누는 이유

  • 대규모 app을 대비하기 위함
  • Server Scaling: 서버를 복제하여 트래픽을 분산
  • Server가 나뉘어있다면 특정 Server에 많은 트래픽이 발생할경우 그 Server만 scalling을 통해 확장이 가능하기에 효율적

Node Server Framework

  • 기본 node에서 제공하는 http 모듈로는 아래코드와 같이 서버 코드를 깔끔하게 구성하기에 한계가 있다.
const http = require('http');
const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    if (req.url === '/api/post') {
      ...
    }
  } else if (req.method === 'POST') {
    ...
  } else if (req.method === 'PUT') {
    ...
  }
  ...
});
  • express는 이러한 서버 코드를 깔끔하게 구성할수 있게 도와주는 프레임워크
const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('hello express');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
profile
Front-End 😲

0개의 댓글