웹 개발

[포스코X코딩온] Web Cookie 실습

끊임없이 성장중인 개발자 2023. 12. 14. 20:05
728x90
반응형

포스팅 주제

  • Web Cookie 실습

이번 실습에서는 모달창을 띄워, 모달창의 오늘 하루안보기를 클릭하면 쿠키에 값의 정보를 주어 클라이언트 웹에 부여한다.

 

< views - index.js >

<!DOCTYPE html>
<html lang="en">

<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 cdn -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous" />
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
    crossorigin="anonymous"></script>

    <!-- jquery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>

  <!-- axios cdn -->
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>

<body>
  <h1>실습. Cookie 연습</h1>
  <p>
    페이지 접속했을 때 위와 같은 창 보이게 하고, “오늘 그만 보기” 선택한 후
    “닫기” 하면 브라우저를 껐다 켜도 창이 보이지 않게 하기
  </p>
  <p>
    개발자도구 > Application > Storage > Cookies > 주소 클릭 후 쿠키를
    삭제했다면 브라우저 새로고침시 alert 창이 나타나야 함!
  </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" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          광고! 어쩌구 저쩌구 <br />
          쿠키 실습
          <div class="text-end mt-3">
            <input type="checkbox" id="cookie" />
            <label for="cookie" style="cursor: pointer">오늘 하루 보지 않음.</label>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeModal();">
            닫기
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 참고) Bootstrap passing option 문서 참고
    // - show(): 수동으로 모달을 엶
    // - hide(): 수동으로 모달 숨김
    // https://getbootstrap.com/docs/5.2/components/modal/#passing-options

    // const myModal = new bootstrap.Modal("#exampleModal");
    const myModal = new bootstrap.Modal(document.getElementById('exampleModal'));
    // myModal.show();
    // const modalToggle = document.getElementById('#exampleModal');
    // myModal.show(modalToggle);


    // console.log(myModal); // _element: div#exampleModal.modal.fade

    // 서버에서 render 할 때 두번째 인자로 보내는 popup 키에 대한 데이터
    console.log('popup >> ', '<%= popup %>');
    // checkbox.checked === true (체크시); ''
    // checkbox.checked === false (미체크시); 'hide'

    // TODO: popup 쿠키 값이 ''이라면, 모달 보여주기
    const popup = '<%= popup %>'
    if(!popup){
      myModal.show();
    }

    // if(popup === ''){
    //   myModal.show()
    // }

    // TODO: 모달 닫기 버튼 클릭 함수 완성
    function closeModal() {
      // 1. 체크 박스가 체크되어 있다면 (오늘 하루 보지 않음을 선택했다면)
      // POST /setCookie 요청 보내기 (back에서 popup 쿠키 설정하기)

      // 1)
      // if(document.getElementById('cookie').checked){
      //   axios({
      //     url: '/setCookie',
      //     method: 'post'
      //   }).then((res) => {
      //     console.log('res.data > ', res.data);
      //   })
      // }
      // myModal.hide();

      const check = document.getElementById('cookie');
      axios({
        method: 'post',
        url: '/setCookie',
        data : {value: check.checked}
      })

      // 2. js로 모달 닫기 수행 (위 참고 링크 확인)
      myModal.hide();
    }
  </script>

<a href="/clearCookie">쿠키 제거하기</a>
<a href="/login">로그인 세션 실습</a>

</body>

</html>

 

pop에 값을 주지 않으면 모달창을 계속 보여준다.

pop에 값이 들어가면 모달창 show를 실행시키지 않기 때문에 closeModal()에서 실행된 hide()값 때문에 모달창이 숨겨진다.

 

모달창의 checkbox를 클릭하고 닫기 버튼을 눌르면 check의 checked 값을 서버로 전송하고 모달창을 숨김

 

< app.js >

const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const app = express();
const PORT = 8000;

app.set('view engine', 'ejs');
app.use('/static', express.static(__dirname + '/static'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const cookieConfig = {
    httpOnly : true,
    maxAge: 24*60*60*1000, //24시간
    signed: true
}

app.use(session({
    secret: 'mySessionSecret',
    resave: false,
    saveUninitialized: true,
    cookie:{
        httpOnly:true,
        maxAge: 24*60*60*1000 // 24시간
    }
}))

// TODO: cookie parser 미들웨어 등록
app.use(cookieParser('mySecretKey')) // 암호화할 값을넣어준다.



app.get('/', (req, res) => {
    // *다음과 같이 기능 구현하였는데, 굳이 이렇게 하지 않아도 됩니다.
    // 모달 체크박스 체크시 -> GET / ; undefined
    // 모달 체크박스 미체크시 -> GET / ; hide
    // console.log('req.cookies.popup >> ', req.cookies.popup);

    // TODO: index.ejs render할 때 두 번째 인자로 popup key 로 요청의 쿠키값 보내기
    console.log("req.cookies.popup >>>",req.cookies.popup);
    console.log("req.signedCookies.popup >>>",req.signedCookies.popup);
    res.render('index', {popup: req.signedCookies.popup});
});

app.post('/setcookie', (req, res) => {
    // TODO: 쿠키 생성
    // 쿠키 이름: 'popup', 쿠키 값: 'hide'
    console.log('req.body.value >>>> ',req.body.value);

    if(req.body.value){
        res.cookie('popup', 'hide', cookieConfig);
    }
    // 1)
    // res.cookie('popup', 'hide', cookieConfig);
    res.send('쿠키 설정 성공!!');
});

app.get('/clearCookie', (req,res) => {
    res.clearCookie('popup','hide', cookieConfig);
    res.send('Clear Cookie!');
});



// ============== 실습2 =================



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

// 힌트
// req 객체
// req.cookies: cookie-parser 미들웨어가 만드는 요청의 쿠키를 해석한 객체
// req.singedCookies: 서명된 쿠키들은 req.cookies 대신 여기에 담겨 있음

// res 객체
// res.cookie(키, 값, 옵션): 쿠키를 설정하는 메서드
// res.clearCookie(키 값, 옵션): 쿠키를 제거하는 메서드

 

만약 모달창의 check 창이 checked 되었다면 해당 값이 req.body.value로 들어오고,

값이 있다면 res.cookie('popup', 'hide', cookieConfig)로 클라이언트에 전송하게 된다.

popup에 값이 들어가기 때문에 index.ejs에서 모달창에 show가 실행이 안되서 쿠키가 사라질 때 까지 모달창이 안보일 것이다.

 

 

 

반응형