나의 발자취

댓글 기능 추가하기 (RestAPI 별도 라우터 /comments) 본문

Backend

댓글 기능 추가하기 (RestAPI 별도 라우터 /comments)

달모드 2024. 10. 15. 10:05

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. 후에 댓글 수정한 후 확인해보기

 

 

728x90
반응형
Comments