[NodeJS] Node.js를 활용한 애니메이션 API 만들기
1. 프로젝트 설정
Node.js를 활용해 애니메이션 API를 만들어 CRUD(Creact, Read, Update, Delete)를 할 수 있는 기능을 만들어보겠습니다. 예시로 MongoDB 데이터베이스를 활용해 만들어보겠습니다. 먼저 Node.js를 설치해줘야합니다.
Node.js — 어디서든 JavaScript를 실행하세요
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
2. 새 프로젝트 생성
프로젝트 폴더에 터미널을 실행해서 Node.js 프로젝트를 생성해줍니다.
mkdir node-anime-api
cd node-anime-api
code .
npm init -y
API를 불러와줄 Epxress.js와 MongoDB의 연결을 위해서 Mongoose를 설치해줍니다.
npm install express mongoose body-parser
프로젝트 폴더내에 index.js를 생성하고 아래 코드를 작성해줍니다.
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// MongoDB 연결
mongoose
.connect("mongodb://localhost:27017/animationDB")
.then(() => console.log("MongoDB Connected"))
.catch((err) => console.error("MongoDB Connect Error", err));
// 애니메이션 스키마 및 모델
const animeSchema = new mongoose.Schema({
title: String,
genre: String,
episodes: Number,
});
const Animation = mongoose.model("Animation", animeSchema);
// API EndPoint
// 1. Animation Add
app.post("/animations", async (req, res) => {
try {
const animation = new Animation(req.body);
await animation.save();
res.status(201).send(animation);
} catch (error) {
res.status(400).send(error);
}
});
// 2. Animation List Search
app.get("/animations", async (req, res) => {
try {
const animation = await Animation.find();
res.status(200).send(animation);
} catch (error) {
res.status(500).send(error);
}
});
// 3. Animation About List Search
app.get("/animations/:id", async (req, res) => {
try {
const animation = await Animation.findById(res.params.id);
if (!animation) return res.status(404).send("Animation Not Found Search");
res.status(200).send(animation);
} catch (error) {
res.status(500).send(error);
}
});
// 4. Animation Update
app.put("/animations/:id", async (req, res) => {
try {
const animation = await Animation.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
if (!animation) return res.status(404).send("Animation Not Found Search!");
res.status(200).send(animation);
} catch (error) {
res.status(400).send(error);
}
});
// 5. Animation Delete
app.delete("/animations/:id", async (req, res) => {
try {
const animation = await Animation.findByIdAndDelete(req.params.id);
if (!animation) {
return res.status(404).send("Animation Not Found Search!");
}
res.status(200).send("Animation Delete!");
} catch (error) {
console.error("Error deleting animation:", error); // 오류 메시지 출력
res.status(500).send(error);
}
});
// search Start
app.listen(PORT, () => {
console.log(`Server is Running http://localhost:${PORT}`);
});
3. 데이터 베이스 설정
MongoDB가 설치되어야합니다. MongoDB 설치가이드를 참고해 설치해주고 아래 명령어로 mongo를 실행합니다.
mongod
서버가 실행 중일때, Postman이나 cURL을 활용해 API를 테스트할 수 있습니다. Postman을 사용해 테스트해보겠습니다. 먼저 Postman을 열고 POST요청으로 실행중인 주소를 보내주고 Body 탭을 클릭해 "raw"를 선택후 "Json"형식을 선택해줍니다. 아래와 같은 JSON 데이터를 입력해주고 다시 Send를 보내줍니다.
{
"title": "Attack on Titan",
"genre": "Action",
"episodes": 75
}
"Send" 버튼을 클릭해주면 응답 탭에서 201 상태 코드와 함께 생성된 애니메이션 데이터가 반환되는지 확인합니다.'
- 애니메이션 조회 (GET)
- 새로운 요청 생성
- URL 입력: http://localhost:3000/animations 입력
- 요청 메서드를 GET으로 선택
- Send를 눌러서 요청 전송(200 상태코드와 애니메이션 목록 반환)
- 새로운 요청 생성
- 애니메이션 상세 조회 (GET)
- 새로운 요청 생성
- URL 입력: http://localhost:3000/animations/{id} 입력
- {id}는 조회할 애니메이션의 id로 대체. ex) http://localhost:3000/67c596e1587e20be3dc8d211
- HTTP 메서드 선택:
- 요청 메서드를 GET으로 선택
- 요청 전송:
- Send 버튼 클릭(200 상태코드와 함께 애니메이션 추가)
- 새로운 요청 생성
- 애니메이션 업데이트 (PUT 요청)
- 새로운 요청 생성
- URL 입력: http://localhost:3000/animations/{id} 입력
- {id}는 업데이트할 ID로 대체
- HTTP 메서드 선택:
- 요청 메서드를 PUT으로 선택
- Body 설정:
- "Body" 탭 클릭 후 "raw"를 선택하고 "JSON" 형식으로 설정
- 데이터 수정(위 JSON 형태와 같이 원하는 대로 수정(선언한 데이터 한정))
- 요청 전송
- "Send" 버튼 클릭후 요청 전송
- 200 상태코드와 함께 데이터 반환 확인
- 새로운 요청 생성
- 애니메이션 삭제 요청(DELETE)
- 새로운 요청 생성
- URL 입력: http://localhost:3000/animations/{id} 입력
- {id}는 삭제할 ID로 대체
- HTTP 메서드 선택
- 요청 메서드를 DELETE로 선택
- 요청 전송
- "Send" 버튼 클릭 후 요청 전송
- 200 상태 코드와 함께 데이터 삭제 확인
- 새로운 요청 생성
GitHub - Koras02/nodejs-anime-api-
Contribute to Koras02/nodejs-anime-api- development by creating an account on GitHub.
github.com