NodeJS study notes: Connect middleware module (1) _ node. js

Source: Internet
Author: User
This is a summary of the Directory, which records the basic knowledge of Node. js. this article and the subsequent articles will be an advanced series. let's build a learning process from a simple perspective, 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.

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

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.

The 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.

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

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

The 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.

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) 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.

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.