내일배움캠프 Spring 3기/웹개발 A to Z

웹개발 A to Z (5) - 웹사이트 배포

yokxim 2024. 8. 16. 16:47

오늘은 웹개발 강의의 마지막 주제인 배포를 해보는 날이다!

 

먼저 4주차 내용때 배운 것들을 복습하는 차원에서 다시 한번 복습해보도록 하자.

Firebase라는 서버에 내 데이터를 저장하고, 저장되어 있는 데이터를 하나씩 읽어온 후 html 코드로 치환하여 카드 형태로 나 웹사이트에 출력되게 하는 예제를 다시 학습해보자.

그리고 오늘은 추가로 다른 코드 변화 없이, Github Pages로 배포하는 방법만 간단하게 알아보도록 하자.

 

 

먼저 지난번에 만들어놨던 영화 소개 홈페이지를 다시 가져와서 작업하자.

먼저 Firebase라는 서버를 사용하기 위해서는 세팅 작업이 필요하다. 그 세팅 작업에 필요한 코드는 다음과 같다.

 

  <script type="module">
    // Firebase SDK 라이브러리 가져오기
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js";
    import { collection, addDoc } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore.js";

    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "AIzaSyAftiw-pWmG1C4Q-fUXowlhOyEtnpR6N2U",
      authDomain: "sparta-e5f34.firebaseapp.com",
      projectId: "sparta-e5f34",
      storageBucket: "sparta-e5f34.appspot.com",
      messagingSenderId: "401566102781",
      appId: "1:401566102781:web:5f45ff16a418853068ba94",
      measurementId: "G-ZQS5NQ3FBQ"
    };

    // Firebase 인스턴스 초기화
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);

 

저 중간에 firbaseConfig라고 적힌 부분은 모두에게 다 다르게 주어진 firebase에서 제공되는 키이므로, 각자 키를 가져와서 저 공간에 복사 붙여넣기를 하면 된다. 저 키를 어떻게 가져와야 하는지 잘 모르겠는 사람들은, 4주차 웹개발 내용을 확인하도록 하자.

 

script 태그에 'module'이라는 타입을 붙여주었다면, 이전에 이 태그 안에 onclick()와 같이 다른 UI와 소통하던 코드들은 작동하지 않게 될 것이다. 이 예시에서 '영화 기록하기'와 같은 코드에 <button onclick="openclose()"...> 라는 코드가 있었다면, 이 코드를 지우고 대신 버튼의 id값을 주자.

 

        <button id="savebtn" type="button" class="btn btn-outline-light">영화 기록하기</button>

나는 여기에 savebtn이라는 아이디값을 줬다.

 

그리고 동적으로 클릭 기능을 구현해 주면 되는데, 이는 어렵지 않다.

    $("#savebtn").click(async function () {
      $('#postingbox').toggle();
    })

 

이렇게 방금 설정한 아이디값을 클릭했을 때, 어떤 아이디값을 가진 오브젝트에 어떤 작업이 수행될지를 적으면 된다.

여기서는 postingbox라는 div 값에 toggle이 수행되도록 했다.

 

그리고 다음으로 Firebase의 내부 기능 중 하나인 addDoc를 활용해서 내가 적은 카드 내용을 데이터베이스에 저장해 보자.

 $("#postingbtn").click(async function () {
            let image = $('#image').val();
            let title = $('#title').val();
            let content = $('#content').val();
            let date = $('#date').val();

            let doc = {
                'image': image,
                'title': title,
                'content': content,
                'date': date
            };
            await addDoc(collection(db, "albums"), doc);
            alert('저장이 완료되었습니다.');
            window.location.reload();
        })

이건 지난번에 album에 사용했던 코드인데, 이 코드를 지금 내 html 정보와 맞게 수정해보려고 한다.

 

  <div class="mypostingbox" id="postingbox">
    <div class="form-floating mb-3">
      <input type="email" class="form-control" id="image" placeholder="영화 이미지 주소">
      <label for="floatingInput">영화 이미지 주소</label>
    </div>
    <div class="form-floating mb-3">
      <input type="email" class="form-control" id="title" placeholder="영화 제목">
      <label for="floatingInput">영화 제목</label>
    </div>
    <div class="input-group mb-3">
      <label class="input-group-text" for="inputGroupSelect01">별점</label>
      <select class="form-select" id="star">
        <option selected>별점선택</option>
        <option value="⭐"></option>
        <option value="⭐⭐">⭐⭐</option>
        <option value="⭐⭐⭐">⭐⭐⭐</option>
        <option value="⭐⭐⭐⭐">⭐⭐⭐⭐</option>
        <option value="⭐⭐⭐⭐⭐">⭐⭐⭐⭐⭐</option>
      </select>
    </div>
    <div class="form-floating mb-3">
      <input type="email" class="form-control" id="comment" placeholder="추천 이유">
      <label for="floatingInput">추천 이유</label>
    </div>
    <button id="postingbtn" type="button" class="btn btn-danger">기록하기</button>
  </div>

이 코드는 내 영화 카드에 들어갈 값들인데, 위에서부터 id 값만 보면 image, title, star, 그리고 comment로 이루어져 있다.

이 값들로 바꿔서 코드를 재작성하면, 

이런 코드가 나온다.

 

  $("#postingbtn").click(async function () {
      let image = $('#image').val();
      let title = $('#title').val();
      let star = $('#star').val();
      let comment = $('#comment').val();

      let doc = {
        'image': image,
        'title': title,
        'star': star,
        'comment': comment
      };
      await addDoc(collection(db, "movies"), doc);
      alert('저장이 완료되었습니다.');
      window.location.reload();
    })

 

이 상태가 되면, 내가 카드 정보를 입력했을 때 '저장이 완료되었습니다'라는 알림과 함께, Firebase 데이터베이스에 영화 정보가 들어간 것을 확인할 수 있다.

 

다음으로는 데이터베이스에 저장된 데이터를 가지고 와서 페이지가 로드되기 직전에 html 코드로 치환되어 카드를 자동으로 만들어주게 할 수 있다. 역시 Firebase에서 제공한 함수인 GetDoc을 사용해서 만들어볼건데, 지난번에 사용했던 코드를 그대로 가져와서 사용해보자.

 

    let docs = await getDocs(collection(db, "albums"));
        docs.forEach((doc) => {
            let row = doc.data();

            let image = row['image'];
            let title = row['title'];
            let content = row['content'];
            let date = row['date'];

            let temp_html = `
            <div class="col">
                <div class="card h-100">
                    <img src="${image}"
                        class="card-img-top" alt="...">
                    <div class="card-body">
                        <h5 class="card-title">${title}</h5>
                        <p class="card-text">${content}</p>
                    </div>
                    <div class="card-footer">
                        <small class="text-muted">${date}</small>
                    </div>
                </div>
            </div>`;
            $('#card').append(temp_html);
        });

 

바로 이 코든데, 여기에서 내가 필요한 정보는 이 페이지에서 사용할 카드의 html 코드 부분이다.

 

<div class="col">
  <div class="card">
          class="card-img-top" alt="...">
      <div class="card-body">
          <h5 class="card-title">영화 제목</h5>
          <p class="card-text">⭐⭐⭐</p>
          <p class="card-text">영화 코멘트</p>
      </div>
  </div>
</div>

 

바로 이렇게 생겼다. 이 친구를 temp_html 코드 안에 넣어주고, image, title, star, comment를 넣어주면 다음과 같은 코드가 된다.

 

   let docs = await getDocs(collection(db, "movies"));
    docs.forEach((doc) => {
      let row = doc.data();

      let image = row['image'];
      let title = row['title'];
      let star = row['star'];
      let comment = row['comment'];

      let temp_html = `
        <div class="col">
        <div class="card h-100">
          <img src="${image}"
            class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title">${title}</h5>
            <p class="card-text">${star}</p>
            <p class="card-text">${comment}</p>
          </div>
        </div>
      </div>`;
      $('#card').append(temp_html);
    });

 

성공했다면, 이제 카드 정보를 입력하면 새로고침을 해도 카드 정보가 사라지지 않고 남아 있는 것을 볼 수 있다.

 

 

=================================

 

이제 번듯한 웹사이트를 만들었으니(아마도) 배포하는 과정을 간단하게 해보려고 한다. 정말 간단하다.

 

먼저 Github 홈페이지에 들어가서, 

https://github.com/

 

GitHub: Let’s build from here

GitHub is where over 100 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and fea...

github.com

회원가입을 하고 Create new repository를 누른다.

그리고 Upload existing files를 눌러서 지금까지 내가 만든 웹사이트 html 파일을 올린다.

Repository를 새로 만들고 파일을 업로드했다면, 파일의 Settings를 찾아가 누른다.

 

그리고 Pages를 찾는다.

그리고 Branch Name을 main으로 설정하고, save 버튼을 누른다.

그리고 조금만 기다리면 이렇게 링크 주소가 나온다.

 

https://yokxim2.github.io/sparta/

 

스파르타플릭스

 

yokxim2.github.io

 

그러면 저 링크로 모든 사람들이 접근해서 내 홈페이지를 볼 수 있게 된다! (부끄러워라)

이제 모든 과정을 마쳤다! HTML 기본은 안다고 어디 가서 말할 수 있게 된거 같아 뿌듯하다. ㅋㅋㅋ