NodeJS Study Notes: Connect middleware module (I), nodejs Study Notes

Source: Internet
Author: User

NodeJS Study Notes: Connect middleware module (I), nodejs Study Notes

I hope you can continue reading my articles in this series. This is also the greatest encouragement and support for me. Let's make common progress and help each other. Now, go to today's topic,

What is "Connect" and how to understand middleware? Let's take a look at today's article with questions.

How to Understand "Middleware "?

In my understanding, middleware is something similar to a filter, a method for processing requests and responses between the client and the application.

If we compare an http processing process to sewage processing, middleware is like a layer-by-layer filter. Each middleware modifies the request or (and) response data during http processing,

Status to implement specific functions.

What is "Connect"?

We can regard Connec as a collection of middleware. For each request, Connect uses the middleware layer to filter requests. Each middleware can obtain HTTP requests.

T. J Holowaychuk talked about Connect, he said there are two types of middleware. One of them is the filter:

Filters process requests, but they do not respond to requests (think about server logs ).

The second type is the provider, which will respond to the request. You can use multiple middleware based on your needs. Http requests will respond to the request through each middleware until one middleware.

2. Introduction to Connect built-in Middleware

The following are some of the main middleware and examples:

(1) cookieParser ------ cookie parsing middleware. parse the cookie header to get Cookies through req. cookies. You can also use req. secret to encrypt cookies.

Copy codeThe 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

Parameter: options

Options:

Key: Cookie name. The default value is connect. sid.

Store: session storage instance

Secret: session cookie Encryption

Cookie: cookie configuration of the session. The default value is {path: '/', httpOnly: true, maxAge: null}

Proxy: Security cookie reverse proxy, implemented through x-forwarded-proto

Cookie option:

Cookie. maxAge: The default value is null, indicating that the cookie is deleted after the browser is closed.

Copy codeThe Code is as follows:
Var connect = require ('./lib/connect ');
Var app = connect ()
. Use (connect. logger ('dev '))
. Use (connect. cookieParser ())
. Use (connect. session ({secret: '000000', cookie: {maxAge: 123 }}))
. 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", the number of "sessions" maintained on the server side increases.

(3) bodyParser ------ request content parsing middleware, supporting multiple types of application/json, application/x-www-form-urlencoded, multipart/form-data.

Copy codeThe 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 );

3. Another comparison instanceTo see the benefits of using middleware.

Copy codeThe Code is as follows:
/*
* Use connect for static File Processing
*/
Var connect = require ('connect ');
Connect (connect. static (_ dirname + '/public'). listen (// listener
8888,
Function (){
Console. log ('connect started on port 8888 ');
}
);
/*
* 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 ('20140901 ');
}
Else {
Res. end (data );
}
}
);
}
). Listen (// listener
8888,
Function (){
Console. log ('HTTP Server started on port 8888 ');
}
);

Although the node native api has spent so much code, it still leaves a simple static file server unhandled in many aspects,

For example, 404 and other exceptions are not handled, there is no basic file path security verification (we can actually access the entire OS file system), and Global exception handling;

At the same time, connect has handled all these problems.

Iv. Summary

(1) understand the middleware stream processing.

Copy codeThe 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) differences between native implementation and middleware implementation.

(3) Use the preceding middleware examples to understand the usage and use cases, and refer to relevant documents to learn about the basic use of other middleware.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.