function setcookie(res, name, val, secret, options) {
var signed = ‘s:‘ + signature.sign(val, secret);
// ....省略
res.setHeader(‘set-cookie‘, header)
}
此处利用set-cookie写入cookie。当客户端发送cookie,此时就用到了parser.js的signedCookies。
exports.signedCookies = function(obj, secret){
var cookies = Object.keys(obj);
var dec;
var key;
var ret = Object.create(null);
var val;
for (var i = 0; i < cookies.length; i++) {
key = cookies[i];
val = obj[key];
dec = exports.signedCookie(val, secret);
if (val !== dec) {
ret[key] = dec;
delete obj[key];
}
}
return ret;
};
exports.signedCookie = function(str, secret){
return str.substr(0, 2) === ‘s:‘
? signature.unsign(str.slice(2), secret)
: str;
};
在帮助函数signedCookie中,当发现含有s:开始则是签名过的cookie,这时就用了signature.unsign解签。下次,让我们来研究一下session。