자바스크립트 fetch API를 사용한 댓글 시스템 구현

댓글 시스템은 웹 애플리케이션에서 사용자들이 서로와 소통할 수 있는 중요한 기능입니다. 자바스크립트 fetch API를 활용하면 쉽게 서버로부터 데이터를 가져와 댓글 시스템을 구현할 수 있습니다.

fetch API란?

fetch API는 웹 브라우저에서 네트워크 요청을 보내고 서버로부터 데이터를 가져오는 기능을 제공하는 API입니다. 기존의 XMLHttpRequest와 비슷한 역할을 수행하지만 간단하고 직관적인 사용법을 가지고 있습니다.

댓글 시스템 구현

1. HTML 마크업

우선 댓글을 표시할 HTML 마크업을 작성해야 합니다. 다음은 간단한 댓글 목록을 표시하는 예시입니다.

<div id="comments">
  <div class="comment">
    <strong>John Doe</strong>
    <p>This is the first comment.</p>
  </div>
  <div class="comment">
    <strong>Jane Smith</strong>
    <p>This is the second comment.</p>
  </div>
</div>

2. 자바스크립트 코드 작성

댓글 시스템을 구현하기 위해 자바스크립트 코드를 작성해야 합니다. fetch API를 사용하여 서버로부터 댓글 데이터를 가져오는 예시 코드를 아래에 제시합니다.

fetch('/api/comments')
  .then(response => response.json())
  .then(data => {
    const commentsContainer = document.getElementById('comments');
    data.forEach(comment => {
      const commentDiv = document.createElement('div');
      commentDiv.classList.add('comment');

      const commenter = document.createElement('strong');
      commenter.textContent = comment.username;

      const commentText = document.createElement('p');
      commentText.textContent = comment.comment;

      commentDiv.appendChild(commenter);
      commentDiv.appendChild(commentText);
      commentsContainer.appendChild(commentDiv);
    });
  })
  .catch(error => console.error('Error:', error));

위의 코드는 ‘/api/comments’ 엔드포인트에서 댓글 데이터를 가져와 댓글 목록을 동적으로 생성합니다. fetch 함수는 서버로부터 응답을 받고, 받은 응답을 json 형식으로 변환하여 처리합니다.

3. 서버 구현

댓글 데이터를 제공하는 서버 엔드포인트를 구현해야 합니다. 이 부분에서는 서버 사이드 기술에 따라 차이가 있을 수 있습니다. 예를 들어, Node.js를 사용한다면 Express.js를 통해 간단하게 라우팅을 설정할 수 있습니다.

const express = require('express');
const app = express();

app.get('/api/comments', (req, res) => {
  // 여기에 댓글 데이터를 가져오는 로직을 작성합니다.
  // 예를 들어, DB에서 댓글 데이터를 조회하여 응답할 수 있습니다.
  const comments = [
    { id: 1, username: 'John Doe', comment: 'This is the first comment.' },
    { id: 2, username: 'Jane Smith', comment: 'This is the second comment.' }
  ];

  res.json(comments);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

위의 코드는 ‘/api/comments’ 엔드포인트에서 미리 정의된 댓글 데이터를 응답합니다. 실제로는 데이터베이스와 연동하여 동적으로 댓글을 가져와야 합니다.

결론

자바스크립트 fetch API는 간편하고 효율적인 방법으로 서버로부터 데이터를 가져올 수 있는 기능입니다. 댓글 시스템 구현에 활용하면 사용자들과 소통할 수 있는 원활한 플랫폼을 구축할 수 있습니다. 위의 예시를 참고하여 자신만의 댓글 시스템을 구현해보세요!