The official statement of the role of cookie-parser is: Parse Cookie header and popular req.cookies with an object keyed by the cookie names. My understanding is to convert cookies in headers and merge them with req.cookies. As the core of cookie-parser, parser prompts 2 functions: signedCookies and JSONCookies, as well as their helper functions.
This article ends this plug-in here. Let’s review it and also open the next article about session learning.
The cookie-parser fetches cookies from the client and then passes through express-session (express-based). On the client, it is represented as a signed string. On the server, since the unsign method is used, you can see the unsigned characters. In this way, all the mystery is unraveled. Let's take a look at the session code that handles cookies.
The code copy is as follows: function setcookie(res, name, val, secret, options) {
var signed = 's:' + signature.sign(val, secret);
// ....Omitted
res.setHeader('set-cookie', header)
}
Here, set-cookie is used to write cookies. When the client sends a cookie, the signed Cookies of parser.js are used.
The code copy is as follows: 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 return;
};
exports.signedCookie = function(str, secret){
return str.substr(0, 2) === 's:'
? signature.unsign(str.slice(2), secret)
: str;
};
In the help function signedCookie, when it is found that it contains s:, it is a signed cookie, and then it is de-signed with signature.unsign. Next time, let's look at the session.
The above is the entire content of node.js cookie-parser parser.js. I hope it can give you a reference and I hope you can support Wulin.com more.