나의 발자취
댓글 기능 추가하기 (RestAPI 별도 라우터 /comments) 본문
1. create_sql에 새로운 DB(comments)를 생성해준다.
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
postId INTEGER,
FOREIGN KEY(postId) REFERENCES posts(id)
);
2. DB 생성된 것 확인
3. 코드 구현
// 특정 포스트 댓글 추가
app.post("/posts/:id/comments", (req, res) => {
const { content } = req.body; // req.body.content -> content
const postId = req.params.id;
const stmt = db.prepare("INSERT INTO comments(postId, content) VALUES (?,?)");
const result = stmt.run(postId, content);
res
.status(201)
.json({ id: result.lastInsertRowid, postId: postId, content: content });
});
4. CURL 넣기
curl -X POST -H "Content-Type: application/json" -d '{"content": "노벨문학상"}' http://localhost:3000/posts/1/comments
그러면 아래와 같이 뜬다.
5. sqlite3에서 스키마 확인
6. 댓글 관련 코드 작성
7. 후에 댓글 수정한 후 확인해보기
'Backend' 카테고리의 다른 글
[Node.js] GraphQL Schema 설계, mutation 타입 (0) | 2024.10.15 |
---|---|
GraphQL 특징, node js로 GraphQL 구현 및 쿼리 날려보기 ⭐️ (0) | 2024.10.15 |
RestAPI에 betterSQL 적용하기 (0) | 2024.10.14 |
RESTful API 설계 후 CURL로 데이터 주고받기 (0) | 2024.10.14 |
CURL이란? (8) | 2024.10.14 |
Comments