Node.js | Express에 의한 요청 처리 기본 | Express에서 쿠키 이용
약간의 데이터 저장에 많이 이용되는 것이 “쿠키"이다. Express는 쿠키를 이용하기 위한 기능이 준비되어 있다. 그 사용법을 설명한다.
Express에서 쿠키
라이브러리로드
"Application".use (express.cookieParser());
쿠키를 이용하면 express의 “cookieParser"을 로드해야 한다. 이걸로 쿠키 정보를 객체로 취급할 수 있게 된다.
쿠키의 저장
"Response".cookie(이름, 값 [,옵션]);
쿠키를 저장하는 경우, Response의 cookie 메소드를 호출한다. 값에 붙이는 이름과 텍스트를 지정하면된다. 세번째 인수에 옵션 설정을 연관 배열로 사용할 수 있다. 예를 들어 쿠키의 유효 기간을 expires 값으로 갖게 할 수 있다.
쿠키의 얻기
"Request".cookies.이름
쿠키의 값은 cookieParser 의해 Request의 “cookies"속성으로 저장된다. 이 중에 쿠키 이름의 속성이 만들어지고 거기에 각각의 값이 저장된다.
그럼 다음에 간단한 사용 예제는 아래와 같다.
routers/helo.js
var express = require('express');
var router = express.Router();
/* GET helo page. */
router.get('/', function(req, res, next) {
var str;
try {
str = req.cookies.lastdata;
} catch(e){}
res.render('helo',
{
title: 'HELO Page',
msg: 'please type...',
cookie: "last:" + str,
input: ''
}
);
});
/* POST helo page. */
router.post('/', function(req, res, next) {
var str = req.body.input1;
res.cookie("lastdata",str,
{ expires: new Date(Date.now() + 600000)});
res.render('helo',
{
title: 'HELO Page',
msg: "you typed: " + str,
cookie: str,
input: str
}
);
});
module.exports = router;
views/helo.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body onload="init()">
<h1><%= title %></h1>
<p><%= msg %></a>
<p><%= cookie %></p>
<form id="form1" name="form1" method="post" action="/helo">
<input type="text" id="input1" name="input1"
value="<%= input %>">
<input type="submit" value="click">
</form>
</body>
</html>
앞전에 /helo를 사용한 예제를 그대로 사용하고 있다.
/helo 폼에 뭔가 쓰게 보내면 그것이 쿠키에 저장된다. 이후, /helo에 액세스하면 저장되어 있던 값이 표시되도록 한다. 여기에 10분 동안 쿠키를 보관할 수 있도록되어 있지만, expires를 조정하여 좀 더 오래 보관 할 수 있다.
여기에서는 helo.js의 router.post에 res.cookie를 사용하여 쿠키를 저장하고, router.get에서 req.cookies.lastdata에서 쿠키 값을 얻어 표시를 수행하고 있다. 쿠키의 사용은 이렇게 Express를 사용하면 대단히 쉽게 할 수 있다.
최종 수정 : 2018-07-16