Nodejs Learning Notes of Connect middleware module (a) _node.js

Source: Internet
Author: User
Tags exception handling

I hope you can insist on watching this series of articles, this is my biggest encouragement and support, let us common progress, Iven, mutual help. Okay, straight into today's theme,

What is "Connect", middleware and how to understand, with questions to see today's article.

How to understand "middleware"?

My understanding is that middleware is something similar to a filter, a method of processing requests and responses between the client and the application.

If an HTTP process is compared to a sewage treatment, the middleware is like a layer of filtering network. Each middleware overwrites the request or (and) response data during HTTP processing.

State to achieve a specific function.

What is "Connect"?

We can think of Connec as a collection of middleware. For each request, connect will use the middleware layer to filter requests, each of which can obtain HTTP requests.

T.J Holowaychuk When it comes to connect, he says there are two types of middleware. One of them is a filter:

The filter processes the request, but they do not respond to the request (think of the server log).

The second type is the provider, which responds to requests, and you can use multiple middleware depending on your requirements, and HTTP requests will respond to the request through each middleware until one of the middleware.

Introduction to connect built-in middleware

Here are a few of the main middleware, and the examples tell:

(1), cookieparser------Cookie parsing middleware, parsing cookies from the head through req.cookies to get cookies. Cookies can also be encrypted via Req.secret.

Copy Code code 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 cookie configuration, default value is {path: '/', Httponly:true, maxage:null}

Proxy: The reverse proxy for secure cookies, implemented by X-forwarded-proto

Cookie option:

Cookie.maxage: The default value is null, which means that the cookie is deleted when the browser is closed.

Copy Code code as follows:

 var connect = require ('./lib/connect ');
 var app = connect ()
 .use (Connect.logger (' dev '))
 .use (Connect.cookieparser ())
&nbs P;. 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, server-side "session" maintenance number.

(3), bodyparser------Request Content parsing middleware, supporting various types of application/json,application/x-www-form-urlencoded, Multipart/form-data.

Copy Code code 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, compare the examples to see the benefits of using middleware.

Copy Code code as follows:

/*
* Using connect to implement static file processing
*/
var connect = require (' Connect ');
Connect (connect.static (__dirname + '/public ')). Listen (//monitor
8888,
function () {
Console.log (' Connect started on port 8888 ');
}
);
/*
* Using the node native API to implement
*/
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;
Reading local Files
Fs.readfile (
Pathname
function (err, data) {
Exception handling
if (err) {
Res.writehead (500);
Res.end (' 500 ');
}
else {
Res.end (data);
}
}
);
}
). Listen (//monitor
8888,
function () {
Console.log (' Http Server started on port 8888 ');
}
);

Although the node native API has cost so many lines of code, it still leaves a lot of aspects of a simple static file server untreated,

For example: 404 Exception unhandled, no basic file path security verification (in fact, we can access the entire OS file system), global exception handling, and so on;

At the same time, connect has dealt with all these problems.

Four, sum up

(1) To understand the streaming processing of middleware.

Copy Code code 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 the native implementation and the middleware implementation.

(3), through the above examples of middleware, understand the use and use of the scene and refer to the relevant documents to grasp the basic use of the rest of the 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.