I hope you can continue to read this series of articles. This is also the greatest encouragement and support for me. Let us make progress together, make friends through literature, and help each other. Okay, let’s go straight to today’s topic,
What is "Connect" and how to understand middleware? Come to today's article with questions.
How to understand "middleware"?
My understanding is this, middleware is something similar to a filter, a method between the client and the application to process requests and responses.
If you compare an http processing process to sewage treatment, middleware is like layers of filters. Each middleware rewrites the request or (and) response data during http processing,
Status implements specific functions.
What is “Connect”?
We can think of Connec as a collection of middleware. For each request, Connect will use a middleware layer to filter the request, each of which can obtain HTTP requests.
When T.J Holowaychuk talked about Connect, he said that there are two types of middleware. One of them is a filter:
Filters handle requests, but they do not respond to requests (think server logs).
The second type is the provider, which will respond to the request. You can use multiple middlewares according to your needs. The HTTP request will pass through each middleware until one of the middlewares responds to the request.
2. Introduction to Connect’s built-in middleware
The following lists several major middlewares and describes them with examples:
(1), cookieParser------cookie parsing middleware, parses the header of Cookies to obtain cookies through req.cookies. Cookies can also be encrypted via req.secret.
(2), session
Description: Session management middleware
Dependency: cookieParser
Parameters: options
options:
Key: Cookies name, the default value is connect.sid
store: session storage instance
Secret: session cookie encryption
Cookie: session cookie configuration, the default value is {path: ‘/’, httpOnly: true, maxAge: null}
Proxy: Reverse proxy for secure cookies, implemented through x-forwarded-proto
Cookie option:
Cookie.maxAge: The default value is null, which means the cookie is deleted when the browser is closed.
As the client continues to refresh the page, "PV" will continue to increase, and the server-side "Session" maintains the number.
(3), bodyParser------request content parsing middleware, supports multiple types of application/json, application/x-www-form-urlencoded, multipart/form-data.
Third, here is another comparison example to see the benefits of using middleware.
At the same time, connect has solved all these problems.
Four, summary
(1), understand middleware streaming processing.
(2), the difference between native implementation and middleware implementation.
(3), through the above examples of middleware, understand the purpose and usage scenarios and refer to relevant documents to master the basic use of other middleware.