brunch

You can make anything
by writing

C.S.Lewis

by 훈오빵 Nov 22. 2023

Node.js 기본서버 만들기(4)

Express로 간단한 API 서버 만들기

**API(Aplication Programming Interface) : 프로그램에서 다른 프로그램의 기능을 사용할 수 있게 해주는 규약

**REST API 원칙 : 자원을 URL에 표현하고 자원을 가져오는 행위를 HTTP 메서드로 표현하는 규칙


1. 게시판 API 코드 작성

(경로), (HTTP메서드), (설명)

/, GET, 게시판 목록 가져오기

/posts, POST, 게시판에 글쓰기.(id, title, name, text, createdDt로 구성)

/posts/:id, DELETE, 게시글 id에 해당하는 글을 삭제


2. API 규칙에 맞게 서버 구현

const express = require("express");
const app = express();
let posts = [ ];            // 게시글 리스트로 사용할 posts에 빈 리스트 할당

// req.body를 사용하려면 JSON 미들웨어를 사용해야 함
// 사용하지 않으면 undefined로 반환
app.use(express.json());        // JSON 미들웨어 활성화

// POST 요청 시 컨텐트 타입이 application/x-www-form-urlencoded인 경우 파싱
app.use(express.urlencoded({ extended: true }));        // JSON 미들웨어와 함께 사용

app.get("/", (req, res) => {                                // /로 요청이 오면 실행
    res.json(posts);                                            // 게시글 리스트를 JSON 형식으로 보여줌
});

app.post("/posts", (req, res) => {                    // posts로 요청이 오면 실행
    const { title, name, text } = req.body;        // HTTP 요청의 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;        // app.delete에 설정한 path 정보에서 id값을 가져옴
   const filteredPosts = posts.filter( (post) => post.id !== +id);    // 글 삭제 로직
   const isLengthChanged = posts.length !== filteredPosts.length;    // 삭제 확인
   posts = filteredPosts;
    if (isLengthChanged) {            // posts의 데이터 개수가 변경되었으면 삭제 성공
       res.json("OK");
        return;
    }
    res.json("NOT CHANGED");        // 변경되지 않음
});

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


3. 게시판 API 테스트하기

3-1. curl로 GET 호출하기

curl -X GET http://localhost:3000


3-2. curl로 POST를 호출해 게시글 등록하기

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "title=제목2&name=andy&text=Node.js입니다." http://localhost:3000/posts


3-3. curl로 DELETE를 호출해 게시글 삭제하기

curl -X DELETE localhost:3000/posts/2


매거진의 이전글 Node.js 기본서버 만들기(3)
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari