-
쿠키 할당하고 출력하기카테고리 없음 2023. 11. 7. 20:01
쿠키란?
set-cookie헤더를 받아 해당데이터를 저장하고 요청을 통해 내보내는것
userId=user-1321;userName=sparta 와 같은 형태로 세미콜론으로 구분한다.
세션이란?
쿠키를 기반으로 구성된 기술로 쿠키과는 다르게 세션은 서버에만 데이터를 저장하기에 보안성이 쿠키보다 좋다.
쿠키 만들어보기
클라이언트의 요청으로 서버는 응답하여 쿠키를 전송하는 형식
res와 cookie 헤더안에 포함 된 정보를 전달받는다.
쿠키할당하기
Set-Cookie을 이용한 쿠키할당하기
app.get("/set-cookie", (req, res) => {
let expire = new Date();
expire.setMinutes(expire.getMinutes() + 60); // 만료 시간을 60분으로 설정합니다.
res.writeHead(200, {
'Set-Cookie': `name=sparta; Expires=${expire.toGMTString()}; HttpOnly; Path=/`,
});
return res.status(200).end();
});이와 같은 형식으로 쿠키를 할당한다.
res.cookie을 이용한 쿠키할당하
app.get("/set-cookie", (req, res) => {
let expires = new Date();
expires.setMinutes(expires.getMinutes() + 60); // 만료 시간을 60분으로 설정합니다.
res.cookie('name', 'sparta', {
expires: expires
});
return res.status(200).end();
});req을 이용한 쿠키접근(할당한 쿠키 사용방법)
app.get("/get-cookie", (req, res) => {
const cookie = req.headers.cookie;
console.log(cookie); // name=sparta
return res.status(200).json({ cookie });
});할당 받은 쿠키를 출력