쿠키는 서버가 만들어서 브라우저가 받아서 사용

정보 덩어리

서버가 브라우저를 구분하기 위한 도구

쿠키 발행하면 쿠키를 발행한 브라우저는 해당 쿠키가 따라감


    console.log(document.cookie);
    // 데이터 구분은 ; 사용
    document.cookie = "user=mj; express=17 Mar 2023 13:00:00 GMT; path=/";
    document.cookie = "test=web; express=17 Mar 2023 13:00:00 GMT; path=/";
		// 쿠키는 만료일을 넘어서 있을 수 없음 (만료일: 오늘)
    console.log(document.cookie);

Untitled


const express = require('express');

const router = express.Router();

//쿠키화면을 보여줌 '쿠키를 팔아요' 화면
router.get('/', (req, res) => {
  res.render('cookie');
});

//클릭을 했을 때 쿠키를 받아주는 라우터
router.get('/cook', (req, res) => {
  //쿠키 발행 코드 작성하기!
  res.cookie('cook', true, {
    expires: new Date(Date.now() + 1000 * 5),
    httpOnly: false,
  });
  res.send('쿠키 굽기 성공!');

});

module.exports = router;
router.get('/cook', (req, res) => {
  res.cookie('alert', true, {
    maxAge: 1000 * 5,
  });
  res.status(200);
  res.json('쿠키 굽기 성공!');
});

<aside> 💡 같이 써도 가능

res.render('cookie'); 프론트

res.send('쿠키 굽기 성공!'); 서버

</aside>

<body>
  <h1>쿠키 팔아요!</h1>
  <input type="checkbox" name="check" id="check" />
  <label for="check">ALERT 하루동안 보지 않기!</label>
</body>
  <script>
    if (!document.cookie) alert('쿠키 팔아요!')
    const checkBox = document.getElementById('check')
    checkBox.addEventListener('click', () => {
      //백엔드에 쿠키 발행을 요청하는 코드 작성하기  
      fetch(`http://localhost:4000/cookie/cook`, {
        method: 'get',
        headers: {
          'Content-type': 'application/json',
        },
      }).then((res) => {
        location.href = '/cookie/cook'
      })
    })
  </script>

Untitled

localhost:4000/cookie/cook 페이지 화면

localhost:4000/cookie/cook 페이지 화면

쿠키가 있어요!

쿠키가 있어요!

Untitled