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 { query } = url.parse(req.url); const { name } = qs.parse(query); 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 { try { const data = await fs.readFile('./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번 포트에서 서버 대기 중입니다!'); });
여기서… parseCookies함수에서 매개변수로 cookie=’’ 이렇게 초기화 하는데 이렇게 하는 이유가 뭔가요? 맨처음 실행할때 쿠키에 값이 없기 때문에 이렇게 한느건가요??
그리고 밑에보면 .split(’;’)되어있는데 개발자 도구 들어가서 요청의 쿠키값 확인해보면 쿠키로 전달되는 값은 {name: xxx}이거 밖에 없는데… 왜 ;이걸로 분리시키나요??
혹시 요청갈때에도 쿠키에 Set-Cookie에 담은 값들 expires나… httpOnly 이런애들 다 같이 가나요?