Node.js Server and Client


Node.js HTTP 서버와 클라이언트 (Node.js HTTP Server and Client)

Node.js는 네트워크 애플리케이션을 구축하는 데 강력한 기능을 제공하며, 특히 HTTP 서버와 클라이언트 개발에 유용합니다. 이 문서에서는 HTTP 프로토콜의 이해, HTTP 서버 생성과 라우팅, Express.js 소개 및 기본 사용법, 그리고 RESTful API 개발에 대해 소개하고 상세히 설명합니다.

HTTP 프로토콜 이해 (Understanding the HTTP Protocol)

HTTP(HyperText Transfer Protocol)는 웹 상에서 데이터를 주고받기 위한 프로토콜입니다. 클라이언트와 서버 간의 요청(Request)과 응답(Response)을 기반으로 작동하며, 주요 메서드에는 GET, POST, PUT, DELETE 등이 있습니다.

  • GET: 서버에서 데이터를 요청합니다.
  • POST: 서버에 데이터를 전송합니다.
  • PUT: 서버에 데이터를 업데이트합니다.
  • DELETE: 서버에서 데이터를 삭제합니다.
HTTP 요청의 구성 (Structure of HTTP Request)

HTTP 요청은 다음과 같은 요소로 구성됩니다.

  • 요청 라인 (Request Line): 메서드, 경로, HTTP 버전으로 구성됩니다.
  GET /index.html HTTP/1.1
  • 헤더 (Headers): 요청에 대한 추가 정보를 제공합니다.
  Host: www.example.com
  Content-Type: application/json
  • 본문 (Body): POST, PUT 요청에서 전송되는 데이터입니다.
  {"name": "John", "age": 30}
HTTP 응답의 구성 (Structure of HTTP Response)

HTTP 응답은 다음과 같은 요소로 구성됩니다.

  • 상태 라인 (Status Line): HTTP 버전, 상태 코드, 상태 메시지로 구성됩니다.
  HTTP/1.1 200 OK
  • 헤더 (Headers): 응답에 대한 추가 정보를 제공합니다.
  Content-Type: application/json
  • 본문 (Body): 서버가 클라이언트에 반환하는 데이터입니다.
  {"message": "Success"}

HTTP 서버 생성과 라우팅 (Creating HTTP Server and Routing)

Node.js에서 HTTP 서버를 생성하려면 http 모듈을 사용합니다. 이 모듈을 사용하여 서버를 생성하고, 요청을 처리하며, 라우팅을 구현할 수 있습니다.

HTTP 서버 생성 (Creating HTTP Server)

간단한 HTTP 서버를 생성하고 실행하는 예제입니다.

const http = require('http');

// 서버 생성
const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

// 서버 실행
server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});
라우팅 구현 (Implementing Routing)

라우팅은 요청된 URL에 따라 다른 처리를 수행하는 것을 의미합니다.

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Home Page\n');
  } else if (req.url === '/about' && req.method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('About Page\n');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Not Found\n');
  }
});

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/');
});

Express.js 소개 및 기본 사용법 (Introduction to Express.js and Basic Usage)

Express.js는 Node.js의 웹 애플리케이션 프레임워크로, 빠르고 간편하게 서버 애플리케이션을 구축할 수 있게 도와줍니다.

Express.js 설치 (Installing Express.js)

Express.js를 설치하려면 npm을 사용합니다.

npm install express
기본 사용법 (Basic Usage)

간단한 Express.js 서버를 생성하고 실행하는 예제입니다.

const express = require('express');
const app = express();

// 기본 라우팅
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

app.get('/about', (req, res) => {
  res.send('About Express');
});

// 서버 실행
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
미들웨어 사용 (Using Middleware)

미들웨어는 요청을 처리하는 중간 단계로, 요청과 응답을 가로채어 처리할 수 있습니다.

const express = require('express');
const app = express();

// 로깅 미들웨어
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 기본 라우팅
app.get('/', (req, res) => {
  res.send('Hello, Express with Middleware!');
});

// 서버 실행
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

RESTful API 개발 (Developing RESTful API)

RESTful API는 HTTP 프로토콜을 사용하여 자원을 관리하는 웹 서비스입니다. Express.js를 사용하여 간단한 RESTful API를 개발할 수 있습니다.

RESTful API 기본 구성 (Basic Structure of RESTful API)

다음은 CRUD(Create, Read, Update, Delete) 기능을 구현하는 RESTful API 예제입니다.

  1. 프로젝트 초기화: npm init 명령어를 사용하여 package.json 파일을 생성합니다.
   npm init -y
  1. Express.js 설치: npm을 사용하여 Express.js를 설치합니다.
   npm install express
  1. RESTful API 구현: server.js 파일을 생성하고 다음 코드를 작성합니다.
   const express = require('express');
   const app = express();

   // 미들웨어 설정
   app.use(express.json());

   // 데이터 저장용 임시 배열
   let items = [];

   // CREATE
   app.post('/items', (req, res) => {
     const item = req.body;
     items.push(item);
     res.status(201).send(item);
   });

   // READ
   app.get('/items', (req, res) => {
     res.send(items);
   });

   app.get('/items/:id', (req, res) => {
     const item = items.find(i => i.id === parseInt(req.params.id));
     if (item) {
       res.send(item);
     } else {
       res.status(404).send({ error: 'Item not found' });
     }
   });

   // UPDATE
   app.put('/items/:id', (req, res) => {
     const item = items.find(i => i.id === parseInt(req.params.id));
     if (item) {
       Object.assign(item, req.body);
       res.send(item);
     } else {
       res.status(404).send({ error: 'Item not found' });
     }
   });

   // DELETE
   app.delete('/items/:id', (req, res) => {
     const index = items.findIndex(i => i.id === parseInt(req.params.id));
     if (index !== -1) {
       const deletedItem = items.splice(index, 1);
       res.send(deletedItem);
     } else {
       res.status(404).send({ error: 'Item not found' });
     }
   });

   // 서버 실행
   app.listen(3000, () => {
     console.log('Server running on http://localhost:3000');
   });

위의 코드는 간단한 RESTful API 서버를 구현한 것으로, items 배열을 사용하여 데이터를 관리합니다. POST, GET, PUT, DELETE 메서드를 사용하여 데이터를 생성, 조회, 수정, 삭제할 수 있습니다.

이 문서에서는 Node.js의 HTTP 서버와 클라이언트를 이해하고, HTTP 프로토콜, 서버 생성과 라우팅, Express.js의 기본 사용법, 그리고 RESTful API 개발에 대해 소개하고 상세히 설명하였습니다. 이러한 지식을 활용하면, Node.js를 사용하여 강력하고 유연한 웹 애플리케이션을 개발할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *