Node.js/NodeJS-book

REST API 서버 만들기

느리지만 꾸준하게 2021. 12. 28. 00:29

서버에 요청 보낼 때 주소를 통해 요청 내용 표현

  • /index.html이면 index.html을 보내달라
  • 항상 html을 요구할 필요는 없음
  • 서버가 이해하기 쉬운 주소가 좋음

 

 

 

REST API(Representational State Transfer)

  • 서버의 자원을 정의하고 자원에 대한 주소를 지정
  • /user이면 사용자 정보에 관한 정보 요청
  • /post이면 게시글에 관련된 자원 요청

 

 

 

HTTP 요청 메서드

  • GET: 서버 자원을 가져오려고 할 때 사용(url 주소창에다가 뭘 쓸때 / 로 구분할 때)

ex)

const http = require('http');
const fs = require('fs').promises;

const users = {}; // 데이터 저장용

http.createServer(async (req, res) => {
  try {
  
  // 아래 부분에서 GET부분 / 형식
    if (req.method === 'GET') {
      if (req.url === '/') {
        const data = await fs.readFile('./restFront.html');
        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
        return res.end(data);
        
      } else if (req.url === '/about') {
        const data = await fs.readFile('./about.html');
        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
        return res.end(data);
      } else if (req.url === '/users') {
        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        return res.end(JSON.stringify(users));
      }
      // /도 /about도 /users도 아니면
      try {
        const data = await fs.readFile(`.${req.url}`);
        return res.end(data);
      } catch (err) {
        // 주소에 해당하는 라우트를 못 찾았다는 404 Not Found error 발생
      }
    } else if (req.method === 'POST') {
      if (req.url === '/user') {
        let body = '';
        // 요청의 body를 stream 형식으로 받음
        req.on('data', (data) => {
          body += data;
        });
        // 요청의 body를 다 받은 후 실행됨
        return req.on('end', () => {
          console.log('POST 본문(Body):', body);
          const { name } = JSON.parse(body);
          const id = Date.now();
          users[id] = name;
          res.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8' });
          res.end('ok');
        });
      }
    } else if (req.method === 'PUT') {
      if (req.url.startsWith('/user/')) {
        const key = req.url.split('/')[2];
        let body = '';
        req.on('data', (data) => {
          body += data;
        });
        return req.on('end', () => {
          console.log('PUT 본문(Body):', body);
          users[key] = JSON.parse(body).name;
          res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
          return res.end('ok');
        });
      }
    } else if (req.method === 'DELETE') {
      if (req.url.startsWith('/user/')) {
        const key = req.url.split('/')[2];
        delete users[key];
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
        return res.end('ok');
      }
    }
    res.writeHead(404);
    return res.end('NOT FOUND');
  } catch (err) {
    console.error(err);
    res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(err.message);
  }
})
  .listen(8082, () => {
    console.log('8082번 포트에서 서버 대기 중입니다');
  });

 

  • POST: 서버 자원을 새로 등록하고자 할 때 사용(또는 뭘 써야할지 모를 때 사용)
  • PUT: 서버 자원을 요청에 들어있는 자원으로 치환할 때 사용(Jay의 관한 모든 정보 다 수정)
  • PATCH: 서버 자원의 일부만 수정할 때 사용( Jay의 나이를 27 => 28로 바꿀때 사용)
  • DELETE: 서버 자원을 삭제할 때 사용

 

POST, PUT, DELETE 요청 보내기

 

 

 

 

 

 

 

 

 

 

<출처 조현영: Node.js 교과서 - 기본부터 프로젝트 실습까지 >

https://www.inflearn.com/course/%EB%85%B8%EB%93%9C-%EA%B5%90%EA%B3%BC%EC%84%9C/dashboard

 

[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지 - 인프런 | 강의

노드가 무엇인지부터, 자바스크립트 최신 문법, 노드의 API, npm, 모듈 시스템, 데이터베이스, 테스팅 등을 배우고 5가지 실전 예제로 프로젝트를 만들어 나갑니다. 최종적으로 클라우드에 서비스

www.inflearn.com

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Node.js > NodeJS-book' 카테고리의 다른 글

Sequelize 모델 만들기  (0) 2022.01.05
Sequelize 사용하기  (0) 2022.01.03
express - middleware 사용해보기  (0) 2021.12.31
express 서버 사용해보기(nodemon error)  (0) 2021.12.31
npm 명령어들  (0) 2021.12.30