Home > Web Front-end > JS Tutorial > body text

NodeJS study notes Connect middleware module (1)_node.js

WBOY
Release: 2016-05-16 16:17:45
Original
1235 people have browsed it

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.

Copy code The code 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, 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.

Copy code The code 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 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. ​

Copy code The code 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, here is another comparison example to see the benefits of using middleware.

Copy code The code is as follows:

/*
* Static file processing using connect
*/
var connect = require('connect');
connect(connect.static(__dirname '/public')).listen(//Listen
8888,
Function() {
console.log('Connect started on port 8888');
}
);
/*
* Implemented 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) {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             .                  }
                    else {
                                                                                                                                                                                           }
            }
);
}
).listen(//Listen
8888,
Function() {
console.log('Http Server started on port 8888');
}
);



Although the node native API has spent so many lines of code, it still leaves many aspects of a simple static file server unaddressed,
For example: 404 and other exceptions are not handled, 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 solved all these problems.

Four, summary

(1), understand middleware streaming processing.

Copy code The code 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), 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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template