실습 - Cookie

YoonSuk Choi·2025년 1월 2일

7주차

목록 보기
4/10

실습 내용

  • 쿠키를 이용하여 특정 조건을 만족할 경우 팝업창을 숨기는 기능을 구현
  • 사용자가 '오늘 그만 보기'를 체크한 후 닫기 버튼을 클릭하면, 해당 정보가 쿠키에 저장 -> 브라우저를 새로고침하거나 다시 실행해도 팝업창이 나타나지 않도록 설정

실습 결과

  1. 페이지에 접속하면 광고 팝업 창이 뜬다.
  2. '오늘 하루 보지 않음'을 체크하고 닫기 버튼을 클릭하면 쿠키가 생성
  3. 브라우저를 재시작하거나 새로고침해도 쿠키가 유지되면 팝업이 나타나지 않음
  4. 쿠키를 삭제한 경우에는 페이지를 새로고침하면 팝업창이 다시 나타난다.

사용한 코드

app.js

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

const PORT = 8080;

app.set("view engine", "ejs");

// 쿠키 미들웨어 설정 예정
app.get("/", (req, res) => {
  res.render("index");
  // 쿠키값 가져오기 및 index.ejs에 보내기
  // res.render("index", {popup:쿠키값});
});

app.post("/set-cookie", (req, res) => {
  // 쿠키 생성 구현 예정
  res.send("쿠키 생성 성공!!!");
});

app.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
});

index.ejs

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>실습</title>

    <!-- Bootstrap 및 Axios 라이브러리 포함 -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <h1>실습. Cookie 연습</h1>
    <p>
      페이지 접속했을 때 팝업 창이 보이며, '오늘 그만 보기'를 체크 후 닫기를 하면 창이 다시 나타나지 않도록 구현합니다.
    </p>

    <!-- Modal: 팝업창 -->
    <div
      class="modal fade"
      id="exampleModal"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">cookie 실습</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            광고! 쿠키 실습입니다.
            <div class="text-end mt-3">
              <input type="checkbox" id="cookie" />
              <label for="cookie">오늘 하루 보지 않음.</label>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" onclick="closeModal();">닫기</button>
          </div>
        </div>
      </div>
    </div>

    <script>
      const myModal = new bootstrap.Modal("#exampleModal");
      myModal.show(); // 팝업창 보임

      async function closeModal() {
        const isChecked = document.getElementById("cookie").checked;
        if (isChecked) {
          await axios.post("/set-cookie");
        }
        myModal.hide(); // 팝업창 닫기
      }
    </script>
  </body>
</html>

코드 설명

  1. app.js에서는 Express를 사용하여 서버를 설정하고, 쿠키를 관리하는 기능을 추가할 예정
  2. index.ejs에서는 Bootstrap을 사용하여 팝업 모달 창을 생성하고, JavaScript 코드로 쿠키 설정 및 팝업 동작을 관리

결론

쿠키를 활용하여 브라우저에서 상태를 유지하는 방법 실습.

profile
Name : 최윤석(YoonSuk Choi)

0개의 댓글