I hope everyone can continue reading my 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. OK, let's go straight to today's topic.
What is "Connect" and how to understand middleware? Let's look at today's article with questions.
How to understand "middleware"?
My understanding is that middleware is something similar to a filter, a way to handle requests and responses between the client and the application.
If an http processing process is compared to sewage treatment, the middleware is like layers of filters. Each middleware rewrites the request or (and) response data during http processing,
state, implements specific functions.
What is "Connect"?
We can think of Connect as a collection of a bunch of middleware. For each request, Connect will use the middleware layer to filter the request, each of which can get the HTTP request.
TJ Holowaychuk said of Connect 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 a provider, which responds to the request. You can use multiple middleware according to your needs. The Http request will respond to the request through each middleware until one of the middleware.
2. Introduction to the built-in middleware of Connect
The following are several main middleware and examples are described:
(1), cookieParser---------------------------------------------------------------------------------------------------------------------- Cookies can also be encrypted via req.secret.
The code copy is as follows:
var connect = require('./lib/connect');
var app = connect()
.use(connect.cookieParser('secret string'))
.use(function (req,res,next){
req.cookies.website="hi,i am bigbear!" ;
res.end(JSON.stringify(req.cookies)) ;
}).listen(8888);
(2), session
Description: Session Management Middleware
Dependency: cookieParser
Parameters: options
options:
key:Cookies name, default value is connect.sid
store: session storage instance
Secret: session cookie encryption
cookie: session's cookie configuration, default value is {path: '/', httpOnly: true, maxAge: null}
proxy: a reverse proxy for secure cookies, implemented through x-forwarded-proto
Cookie option:
cookie.maxAge: The default value is null, indicating that the cookie is deleted when the browser is closed.
The code copy is as follows:
var connect = require('./lib/connect');
var app = connect()
.use(connect.logger('dev'))
.use(connect.cookieParser())
.use(connect.session({secret: '123', cookie: { maxAge: 60000 }}))
.use(function (req, res, next) {
if(req.session.pv){
res.setHeader('Content-Type', 'text/html');
res.write('views: ' + req.session.pv);
res.end();
req.session.pv++;
}else{
req.session.pv = 1;
res.end('Refresh');
}
})
.listen(8888);
As the client continuously refreshes the page "PV" and the number of maintenance on the server side "Session" will continue to increase.
(3), bodyParser-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The code copy is as follows:
var connect = require('connect');
var app = connect()
.use(connect.bodyParser())
.use(function(req, res) {
res.end('req.body=>' + JSON.stringify(req.body));
})
.listen(8888);
Third, let’s take a comparison example and see the benefits of using middleware.
The code copy is as follows:
/*
* Static file processing implemented using connect
*/
var connect = require('connect');
connect(connect.static(__dirname + '/public')).listen(//listen
8888,
function() {
console.log('Connect started on port 8888');
}
);
/*
* Implementation using node native API
*/
var http = require('http');
http.createServer(
function(req, res) {
var url = require('url');
var fs = require('fs');
var pathname = __dirname + '/public' + url.parse(req.url).pathname;
//Read local files
fs.readFile(
pathname,
function(err, data) {
//Exception handling
if (err) {
res.writeHead(500);
res.end('500');
}
else {
res.end(data);
}
}
);
}
).listen(//listen
8888,
function() {
console.log('Http Server started on port 8888');
}
);
Although the node native API has already spent so many lines of code, it still leaves many aspects of a simple static file server that have not been processed.
For example: 404 and other exceptions are not processed, there is no basic file path security verification (in fact, we can access the entire Os file system), global exception handling, etc.
At the same time, connect has already handled all these problems.
Four, let's summarize
(1) Understand middleware streaming processing.
The code copy is as follows:
var app = connect();
app.use(connect.staticCache());
app.use(connect.static(__dirname + '/public'));
app.use(connect.cookieParser());
app.use(connect.session());
app.use(connect.query());
app.use(connect.bodyParser());
app.use(connect.csrf());
app.use(function (req, res, next) {
// middleware
});
app.listen(8888);
(2) Differentiation between native implementation methods and middleware implementations.
(3) Through the above examples of middleware, we can understand the uses and usage scenarios and refer to relevant documents to master the basic use of other middleware.