상세 컨텐츠

본문 제목

[Node.js] Express로 간단한 API 서버 만들어보기

Node.js

by 래모 2024. 7. 22. 13:20

본문

본 게시물은 [Node.js 백엔드 개발자 되기 ]도서를 보고 작성되었습니다.


express 설치

npm i express
yarn add express

 

 

express 실행!

 

express도 require("express")로 불러오고

app = epxress()를 통해 사용된다

 

express로 간단한 API를 만들어보자!

경로 HTTP 메서드 설명
/ get 게시판 목록을 가져옴
/posts post 게시판에 글을 쓴다
글은 id, title, name, text, createdDT로 구성
/posts/:id delete 게시글 아이디가 id인 글 삭제

 

 

 

 

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 미들웨어와 함께 사용

posts에 빈 배열을 할당하고 express.json()을 통해 JSON 미들웨어를 활성화해준다

 

왜 JSON 미들웨어를 활성화하냐?

익스프레스에서 미들웨어는 요청과 응답 사이에 로직을 추가할 수 있는 함수를 제공한다

HTTP 요청 시마다 로그를 남기는 작업을 하고 싶을 때 PAI 코드에 로그를 남기는 작업을 넣기보다는 로그를 남기는 미들웨어를 추가하면 된다!!

 

unlencoded부분을 통해 컨텐트 타입이 application/x-www-form-unlencoded인 경우 파싱해준다

POST 요청의 대부분이 저 타입

 

application/x-www-form-unlencoded는 키=값&키=값 요런 형태를 말한다

 

 

 

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 })
})

/로 get 요청이 오면 posts를 json형태로 넘겨주고

 

/post로 post 요청이 오면 body 데이터를 변수에 할당한다

이후 posts 배열에 push 해준다

 

(res.end()함수의 인수로는 문자열과 바이트 버퍼 형식만 넣을 수 있다)

 

 

app.delete("/posts/:id", (req, res) => {
    const id = req.params.id // app.delete에 설정한 path 정보에서 id값을 가져옴
    const filteredPosts = posts.filter((post) => post.id !== +id) // 글 삭제 로직(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!")
})

delete 요청이 오면 id 정보를 받아와서 배열을 다시 정의 해준다

 

 

 

 

curl로 호출해보기

curl localhost:3000

 

처음엔 이렇게 빈 배열이 보여진다

 

 

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "title=제목1&name=juhui&text=조주연바보" http://localhost:3000/posts
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "title=제목2&name=조주연&text=감자" http://localhost:3000/posts

요런식으로 데이터를 추가함

 

 

저렇게 넣고 나면 localhost:3000에 접속했을 때 데이터가 뜬다

 

curl -X DELETE localhost:3000/posts/1

데이터 삭제는 이렇게!

 

'Node.js' 카테고리의 다른 글

[Node.js] 라우터 만들기  (0) 2024.07.21
[Node.js] Node.js 입문!!  (1) 2024.07.12

관련글 더보기