티스토리 뷰

JavaScript/JS백엔드

Express로 API 만들기

염두리안 2024. 12. 28. 13:20
728x90
반응형
  • 라우트: 특정 엔드포인트를 담당하는 코드
  • app.js
import express from 'express';

const app = express();

// 첫번째 파라미터: url 경로 | 두번째 파라미터: 실행할 콜백함수
app.get('/hello', (req, res) => {
    res.send('Hello Express!');
});

// 3000: 포트 번호
app.listen(3000, () => console.log('Server Started'));
  • 쿼리스트링 처리하기
    • 쿼리스트링? url에서 물음표(?) 뒤에 오는 부분
import express from 'express';
import tasks from './data/mock.js'

const app = express();

app.get('/tasks', (req, res) => {
    /**
     * 쿼리 파라미터
     * - sort: 'oldest'인 경우 오래된 태스크 기준, 나머지 경우 새로운 태스크 기준
     * - count: 태스크 개수
     */

    const sort = req.query.sort;
    const count = Number(req.query.count);

    const compareFn =
        sort === 'oldest'
            ? (a, b) => a.createdAt - b.createdAt
            : (a, b) => b.createdAt - a.createdAt;
    let newTasks = tasks.sort(compareFn);

    if (count) {
        newTasks = newTasks.slice(0, count);
    }
    res.send(newTasks);
});

app.listen(3000, () => console.log('Server Started'));
  • 다이나믹 url 처리하기
    • 다이나믹 url: url이 항상 일정하지 않고 일부가 바뀌는 것
app.get('/tasks/:id', (req, res) => {
    const id = Number(req.params.id);
    const task = tasks.find((task) => task.id === id);
    if (task){
        res.send(task);
    } else {
        res.status(404).send({ message: `Can't find given id.` });
    }
});
  • POST 리퀘스트 처리하기
app. use(express.json());

app.post('/tasks', (req, res) => {
    const newTasks = req.body;
    const ids = tasks.map((task) => task.id);
    newTasks.id = Math.max(...ids) + 1;
    newTasks.isComplete = false;
    newTasks.createdAt = new Date();
    newTasks.updatedAt = new Date();

    tasks.push(newTasks);
    res.status(201).send(newTasks);
});
  • PATCH 리퀘스트 처리하기
app.patch('/tasks/:id', (req, res) => {
    const id = Number(req.params.id);
    const task = tasks.find((task) => task.id === id);
    if (task){
        Object.keys(req.body).forEach((key) => {
            task[key] = req.body[key];
        });
        task.updatedAt = new Date();
        res.send(task);
    } else {
        res.status(404).send({ message: `Can't find given id.` });
    }
});
  • DELETE 리퀘스트 처리하기
app.delete('/tasks/:id', (req, res) => {
    const id = Number(req.params.id);
    const idx = tasks.findIndex((task) => task.id === id);
    if (idx >= 0){
        tasks.splice(idx, 1);
        res.sendStatus(204);
    } else {
        res.status(404).send({ message: `Can't find given id.` });
    }
});
728x90
반응형

'JavaScript > JS백엔드' 카테고리의 다른 글

Prisma와 관계  (0) 2025.01.02
관계형 DB 기본  (0) 2025.01.02
Prisma 기본  (1) 2025.01.01
MongoDB 사용하기  (0) 2025.01.01
Todo API 문서 | 구독 관리 API 문서  (0) 2024.12.24
최근에 올라온 글
최근에 달린 댓글
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Total
Today
Yesterday
반응형