gengminy
갱미니의 코딩일지
gengminy
전체 방문자
오늘
어제
  • 분류 전체보기 (61)
    • 🚀 프로젝트 (16)
      • 🎸 고스락 티켓 (4)
      • 🌞 내친소 (5)
      • 🥁 두둥 (7)
    • 📡 백엔드 (31)
      • 🌱 Spring Boot (13)
      • 🐱 Nest.js (10)
      • ⭐ Node.js (8)
    • 🏭 Infra (11)
      • ⚙ 준비를 위한 준비 (2)
      • 🥑 AWS (3)
      • 🐳 Docker (3)
      • ⚡ Github Actions (3)
    • 🌊 프론트엔드 (1)
      • 🌌 React.js (1)
    • 😎 주저리 (2)

블로그 메뉴

  • 💻Github
  • 📸Instagram
  • ✨Blog

공지사항

인기 글

태그

  • github
  • 스프링부트
  • 네스트
  • 도커
  • OAuth
  • docker
  • 슬랙알림
  • 스프링
  • JSON
  • Spring
  • nestjs
  • SlackAPI
  • springboot
  • oauth2
  • 깃헙액션
  • nodejs
  • AWS
  • JWT
  • nest
  • GithubActions

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
gengminy

갱미니의 코딩일지

📡 백엔드/⭐ Node.js

[Nodejs] http 모듈로 간단한 REST API 사용

2022. 5. 15. 21:20

✅ http 모듈 불러오기

const http = require('http');

✅ http 서버 생성

const http = require('http');
const PORT = 8080;

http.createServer(async (req, res) =>{
    res.writeHead(200, {'Content-Type' : 'text/html; charset=utf-8'});
    return res.end("<h1>hello my server</h1>");
}
).listen(PORT, ()=>{
    console.log(`server online on port ${PORT}!`);
});

header 에 http status를 같이 담아서 전송

 

 

💻console

💻client

- localhost:8080

 

✅ REST API?

REpresentational State Transfer 의 약자
서버의 자원을 정의하고 자원에 대한 주소를 지정하는 방법

  • GET : 서버 자원을 가져옴
  • POST : 서버에 자원을 새로 등록
  • PUT : 서버의 자원을 요청에 들어있는 자원으로 치환
  • PATCH : 서버 자원의 일부만 수정
  • DELETE : 서버 자원을 삭제
  • OPTIONS : 요청을 하기 전에 통신 옵션을 설명하기 위해 사용

 

🔨 간단한 사용 예시

if (req.method === 'GET'){
    if (req.url === '/'){
        const data = await fs.readFile('./src/restFront.html');
        res.writeHead(200, {'Content-Type' : 'text/html; charset=utf-8'});
        return res.end(data);           
    }
} else if (req.method === 'POST'){
    if (req.url === '/user'){
        let body = '';
        req.on('data', (data)=>{
        body += data;
        });
    }
    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('등록 완료');
    });
} 

req.method 에서 메소드 방식을 참조함

저작자표시 (새창열림)

'📡 백엔드 > ⭐ Node.js' 카테고리의 다른 글

[Nodejs] Sequelize 로 SQL 데이터베이스 연동하기  (0) 2022.05.21
[Nodejs] Router 객체로 라우팅 파일 분리  (0) 2022.05.17
[Nodejs] 미들웨어의 사용과 자주 쓰이는 미들웨어  (0) 2022.05.16
[Nodejs] express 서버 열기  (0) 2022.05.15
[Nodejs] 쿠키와 세션  (2) 2022.05.15
    '📡 백엔드/⭐ Node.js' 카테고리의 다른 글
    • [Nodejs] Router 객체로 라우팅 파일 분리
    • [Nodejs] 미들웨어의 사용과 자주 쓰이는 미들웨어
    • [Nodejs] express 서버 열기
    • [Nodejs] 쿠키와 세션
    gengminy
    gengminy
    코딩

    티스토리툴바