Express middleware "cookie-parser" 란 무엇인가?

cookie-parser


cookie-parser 란 무엇인가?

cookie-parser 는 Express에서 자주 쓰이는 미들웨어 중 하나이다.

이 cookie-parser 미들웨어는 cookie를 엄청나게 쉽게 다룰 수 있게 해준다.


cookie-parser의 기능

cookie-parser는 request에서 온 cookies를 parse하고,

req.cookies에 cookies를 Javascript Object 형태로 저장한다.

또한, res.cookie로 cookie를 response에 set할 수 있다.


cookie-parser의 사용 형태
  • var cookieParser = require('cookie-parser');
  • app.use(cookieParser([secret]);

위에 있는 secret은 (optional) string parameter 인데,

이는 secret string을 사용해서 cookie tampering을 막는데에 사용된다.


cookie를 response에 set 하는 방법

res.cookie(name,value,[options]);

options property에 들어가는 것들은 다음과 같다.

• maxAge: Specifies amount of time in milliseconds for the cookie to live before it expires.
• httpOnly: Boolean, when true Express tells the browser that this cookie should only be accessed by the server and not client side JavaScript.
• signed: Boolean, when true the cookie will be signed and you will need to access it using the req.signedCookie object instead of the req.cookie object.
• path: The path that the cookie applies to.

cookie-parser 사용 예

(https://github.com/expressjs/cookie-parser?_ga=1.73535698.1177589384.1426667020)

(1)
var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

app.listen(8080)

(2)
res.cookie('hasVisited', '1',

    { maxAge: 60*60*1000,

        httpOnly: true,

        path:'/'});



cookie를 삭제하는 방법
 res.clearCookie()
ex)  res.clearCookie('hasVisited');