본문 바로가기

IT/javascript

[EXPRESS]간단한 API 서버

반응형

express 를 이용한 간단한 메모리 기반 서버 만들기

 

mkdir api-server

cd api-server

npm i express #현재기준 express version : 4.18.2

#board.js 파일 생성

const express = require("express");
const app = express();
let posts = [];

app.use(express.json()) //req.body 이용하기위해서 미들웨어 지정
app.use(express.urlencoded({ extended: true })); //post 요청시 application/x-www-form-urlencoded 파싱

app.get("/", (req, res) => {
  res.json(posts);
});

app.post("/posts", (req, res) => {
  const { title, name, text } = req.body;

  posts.push({ id: posts.length + 1, title, name, text, createdDt: Date() });
  res.json({ title, name, text });
});

app.delete("/posts/:id", (req, res) => {
  const id = req.params.id;
  const filteredPosts = posts.filter((post) => post.id !== +id); //+연산자를 이용해 문자를 숫자로 바꿈 parseInt 와 동일 parseInt(id)
  const isLengthChanged = posts.length !== filteredPosts.length;
  posts = filteredPosts;
  if (isLengthChanged) {
    res.json("OK");
    return;
  }
  res.json("NOT CHANGED");
});

app.listen(3000, () => {
  console.log("welcome posts START");
});

 

node board.js 로 서버 실행 후,

아래 스크립트로 데이터 넣고 빼기 테스트!

조회

curl -X GET http://localhost:3000

등록 -> 최소 3개를 해본다.

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "title=제목01&name=KJB&text=안녕하세요~" http://localhost:3000/posts

삭제 -> 2번 연속으로 해봐서 메시지가 달라지는 것을 확인한다!

curl -X DELETE http://localhost:3000/posts/2

반응형