I previously joined a study notebook group to share my learning results through study notes. Send one here too.
When we write a web, we will inevitably need to use cookies. Since node.js has the express web framework, we can easily build websites. When using express, the cookie-parser plug-in is often used. Today we will analyze this plug-in.
This plugin is usually used as a middleware, app.use(cookieParser()), so that it can handle every requested cookie.
Judging from the name, this is a tool to explain cookies. Req.cookies can retrieve the passed cookies and convert them into objects. Next, let’s dive into its source code.
First, let's look at index.js
The copy code code is as follows: var cookie = require('cookie');
var parse = require('./lib/parse');
There are 2 references here, one is cookie and the other is the core function of cookie-parser. The cookie module only provides 2 methods, one is serialize and the other is parse.
The serialize method receives key and val and serializes it.
The code copy is as follows: var hdr = cookie.serialize('foo', 'bar'); // hdr = 'foo=bar';
Paser method converts strings into objects
The code copy is as follows: var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); // cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' };
Let’s look at the following, which is the main function cookiePaser of cookie-parser.
The code copy is as follows: exports = module.exports = function cookieParser(secret, options){
return function cookieParser(req, res, next) { // Get the req, res object from the request
if (req.cookies) return next(); // If there is already a cookie object, exit the middleware and continue running
var cookies = req.headers.cookie; // Get cookies from headers
req.secret = secret; // If there is a secret passed in, set to the req object
req.cookies = Object.create(null); // Create an empty object to req.cookies
req.signedCookies = Object.create(null); // Create an empty object to req.signedCookies
// no cookies
if (!cookies) { // If you don't get cookies from headers
return next(); // Exit the middleware and continue running
}
req.cookies = cookie.parse(cookies, options); // Call cookie parse to convert cookie string into cookies object.
// parse signed cookies
if (secret) { // If secret is set, use the two methods of parse to sign the cookie.
req.signedCookies = parse.signedCookies(req.cookies, secret);
req.signedCookies = parse.JSONCookies(req.signedCookies);
}
// parse JSON cookies
req.cookies = parse.JSONCookies(req.cookies); // Convert req.cookies object
next();
};
};
After reading this main function, we are still a little confused, which happens to be its main file parse.js. Let's look at what this file is for next time.
The above is the entire content of the node.js cookie-parser middleware. I hope it can give you a reference and I hope you can support Wulin.com more.