Express REST-API

SSAD·2023년 2월 13일
0

BackEnd

목록 보기
5/44
post-thumbnail

Express 게시글 REST-API 만들기

index.js

import express from "express";

const app = express();

// express는 기본적으로 json 데이터 지원하지 않음
// json을 읽어오기 위해 앱에 추가
app.use(express.json());

const port = 3000;

const boardDB = [
  {
    number: 1,
    writer: "any",
    title: "some",
    contents: " Hello I'm any",
  },
  {
    number: 2,
    writer: "pay",
    title: "help",
    contents: " Some body Help me",
  },
  {
    number: 3,
    writer: "load",
    title: "yes",
    contents: " loading",
  },
];

// 게시글 전체 조회하는 로직
// app.get(엔드포인트, 미들웨어함수)
app.get("/boards", (req, res) => {
  // 미들웨어 함수
  res.send([...boardDB]);
});

// 게시글 등록하는 API
app.post("/boards", (req, res) => {
  const { writer, title, contents } = req.body;

  boardDB.push({
    number: boardDB.length + 1,
    writer,
    title,
    contents,
  });

  res.send({ ...boardDB[boardDB.length - 1] });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Postman으로 확인하기

GET 요청

POST 요청

GET 요청으로 확인

profile
learn !

0개의 댓글