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。