아직까지는 단순한 쿠키만 심었을 뿐이며, 그 쿠키가 나인지 식별해주지는 못하고 있습니다. 다음 예제에서 사용자를 식별하는 방법을 알아봅시다. 다음 두 파일을 같은 폴더 안에 생성합니다.

    cookie2.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title>쿠키&세션 이해하기</title>
    </head>
    <body>
    <form action="/login">
        <input id="name" name="name" placeholder="이름을 입력하세요" />
        <button id="login">로그인</button>
    </form>
    </body>
    </html>

    cookie2.js

    const http = require('http');
    const fs = require('fs').promises;
    const path = require('path');
    
    
    const parseCookies = (cookie = '') =>
      cookie
        .split(';')
        .map(v => v.split('='))
        .reduce((acc, [k, v]) => {
          acc[k.trim()] = decodeURIComponent(v);
          return acc;
        }, {});
    
    http.createServer(async (req, res) => {
      const cookies = parseCookies(req.headers.cookie);

     

      // 주소가 /login으로 시작하는 경우
      if (req.url.startsWith('/login')) {
        const url = new URL(req.url, 'http://localhost:8084');
        const name = url.searchParams.get('name');
        const expires = new Date();
        // 쿠키 유효 시간을 현재 시간 + 5분으로 설정
        expires.setMinutes(expires.getMinutes() + 5);
        res.writeHead(302, {
          Location: '/',
          'Set-Cookie': `name=${encodeURIComponent(name)}; Expires=${expires.toGMTString()}; HttpOnly; Path=/`,
        });
        res.end();

     

      // 주소가 /이면서 name이라는 쿠키가 있는 경우
      } else if (cookies.name) {
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(`${cookies.name}님 안녕하세요`);
      } else { // 주소가 /이면서 name이라는 쿠키가 없는 경우
        try {
          const data = await fs.readFile(path.join(__dirname, 'cookie2.html'));
          res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
          res.end(data);
        } catch (err) {
          res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
          res.end(err.message);
        }
      }
    
    })
      .listen(8084, () => {
        console.log('8084번 포트에서 서버 대기 중입니다!');
    });
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.