백앤드/Node.js

[포스코x코딩온] 웹개발자 입문 과정 7주차 | Cookie

영최 2023. 4. 12. 14:56
728x90

1.Cookie란?

 웹 브라우저(클라이언트)에 저장되는 키와 값이 들어있는 작은 데이터 파일로,

 이름, 값, 만료일, 경로 정보로 구성되어 있다.

 

 - 쿠키 확인 방법: 개발자 도구 > Application > 쿠키

쿠키 확인

 가.  필요성 및 사용 예시

  웹서버는 접속한 클라이언트가 누군지 매번 확인해야하는 문제가 있다.

  이를 해결하기 위해 쿠키나 세션을 이용해서 클라이언트의 정보를 유지시킨다.

 

  예시

  • 로그인 상태 유지
  • 오늘 그만 보기 체크 -> 더이상 창 안띄움

 

 나.동작 방식

 

쿠키 동작 방식

 

.설치 방법

npm install cookie-parser

 

 .사용 방법

  app.js

const express = require("express");
const app = express();
const PORT = 8000;

app.set("view engine", "ejs");
app.use("/views", express.static(__dirname + "/views"));
app.use("/static", express.static(__dirname + "/static"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// 1. cookie-parser 모듈 불러오기
//: 요청의 쿠키를 해석해서 req.cookies 객체로 만듦
// ex. name=hello 라는 쿠키를 보내면, req.cookies => {name: 'hello'}
const cookieParser = require("cookie-parser");

//2. cookiParser 설정
//cookiParser(secretKey, optionObj);
// - secretKey: 비밀키
// - optionObj: 쿠키에서 사용할 옵션 값
app.use(cookieParser()); //req.cookies 가능 해짐


//3. 쿠키 option 설정
const cookieConfig = {
  httpOnly: true, //웹 서버를 통해서만 쿠키 접근 가능 DOC 막음
  maxAge: 60 * 1000, //쿠키 수명 (ms 단위) 1분
  //expires: 만료 날짜 설정
  //secure: https에서만 쿠키 접근
  //signed: 쿠키 암호화
};

app.get("/", (req, res) => {
  res.render("index");
});




//4. 쿠키 설정
//: 쿠키 "설정" 할 때 사용하는 메서드
//res.cookie(key, value, options)
app.get("/setCookie", (req, res) => {
  // 쿠키 설정
  res.cookie("my first cookie", "cookie value test", cookieConfig);
  // 클라이언트 응답 보냄
  res.send("쿠키 설정 완료!!");
});

//5. 쿠키 확인
app.get("/getCookie", (req, res) => {
  //req.cookies
  //: cookie-parser 모듈이 만든 요청의 쿠키를 읽어옴
  res.send(req.cookies);
  //만약 키의 값을 불러오고 싶다면
  //res.send(req.cookies.my first cookie)
});

//6.쿠키 삭제
//: 쿠키 "삭제" 할 때 사용하는 메서드
//res.clearCookie(key, value, options)
app.get("/clearCookie", (req, res) => {
  //쿠키 삭제
  //clearCookie 할때 , res.cookie() 설정했던 key & value & option 일치해야함
  //(단, option에서 expires, maxAge 옵션은 일치하지 않아도 됨)
  res.clearCookie("my first cookie", "cookie value test", cookieConfig);
  //클라이언트 응답
  res.send("쿠키 삭제 완료!!");
});

app.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
});
  1. 쿠키 parser 모듈 불러오기 : const cookieParser = require("cookie-parser");
  2. cookieParser 설정 : app.use(cookieParser());
  3. 쿠키 option 설정: const cookieConfig = { ... };
  4. 쿠키 설정: res.cookie("키", "값", cookieConfig);
  5. 쿠키 확인: req.cookie or req.cookie.key
  6. 쿠키 삭제: res.clearCookie("키", "값", cookieConfig);

쿠키는 하나의 키와 값만 전송 가능하다.

728x90