javaScript/nodeJs

nodejs express // #3 cookie, session 다루기

부엉이사장 2022. 7. 2. 20:01
const cookieParser = require('cookie-parser');
const session = require('cookie-parser');
const dotenv = require('dotenv');

이렇게 모듈들을 가져왔다.

 

 

app.use(express.json());
app.use(express.urlencoded({extended : false}));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(session({
    resave:false,
    saveUninitialized : false,
    secret: process.env.COOKIE_SECRET,
    cookie : {
        httpOnly : true,
        secure : false
    },
    name : 'session-cookie'
}))

쿠키와 세션, 그리고 제이슨, 다 미들웨어 설정 마쳐주었다.

 

사전세팅

index.html에 폼 태그 만들기.

    <form method = "post" action="/">
        <input type="text" name="name" id="">
        <input type="submit">
    </form>

이렇게 폼을 만들어주고

app.post('/', (req, res)=>{
    console.log(req.body.name);
    res.redirect('/');
})

이렇게 하면 req.body.name으로 인풋값을 가져올 수 있다.

나는 이걸 쿠키와 세션에 각각 저장해볼것이다.

 

# 쿠키장난

app.post('/', (req, res)=>{
    console.log(req.body.name) //이렇게 가져올수 있음.
    res.cookie('others', req.body.name, cookObj);
    res.redirect('/');
    // console.log(req.cookies)
})
이렇게 post요청에 others라는 키값을 가지고 value값은 아까 가져온 인풋값 req.body.name을 넣었다.
cookObj는 
const cookObj = {
    expires : new Date(Date.now()+900000),
    httpOnly : true,
    secure : true
}

이거 함수 외곽에 만들어줌.. 쿠키 보안이랑 유지기간 설정하는거임.

 

암튼 그렇게하고 인풋값에 암거나 입력해보자.

hihi를 입력했다. 그리고 개발자도구에서 확인을 해보면

쿠키가 들어간다.

 

여기서 res.redirect를 안해서 쿠키가 첨엔 안들어가는줄 알았다.

새로고침해야 데이터를 받아오니까..

 

++ 쿠키객체 가져오기

app.get('/',(req,res)=>{
    res.sendFile(path.join(__dirname,'/index.html'));
    console.log(req.cookies)
})

req.cookies로 하면

이렇게 객체로 가져와준다.

 

+쿠키삭제

    if(req.body.del){
        res.clearCookie('others',req.cookies.others,delCookObj)
    }

여기서 delCookObj는

const delCookObj = {
    httpOnly : true,
    secure : true
}
요러케 생겼다
 
req.body.del은 html 폼에 del이름의 체크박스만든거다.
체크박스 클릭하고 전송하면 req.body.del이 on이되고 안클릭하면 undefined가 된다.
체크박스 클릭하고 전송하면 others키값의 쿠키가 사라져버린다~
 
 
 

 

# 세션

세션은 아직 잘 활용못하겠다.. 덜배워서..

app.use(session({
    resave:false,
    saveUninitialized : false,
    secret: 'secret key',
    cookie : {
        httpOnly : true,
        secure : false
    },
    name : 'session-cookie'
}))
세션설정
req.session.name = 'tired';

이렇게  세션에 추가하면

 

 

브라우저에 암호화되서 추가된다.

 

 

이건 실제 로그인 구현하면서 공부해야할듯