From: http://www.expressjs.com.cn/guide/using-middleware.html#middleware.application
Express is a minimalist web development framework that is entirely composed of routing and middleware: Essentially, an express application is invoking a variety of middleware.
The Middleware (middleware) is a function that accesses the request object (req), the Response object (Response object (res)), and the middleware in the Web application that is in the request-response loop process. A variable that is generally named next.
The middleware features include: Execute any code. Modifies the request and response objects. The end request-response loop. The next middleware in the call stack.
If the current middleware does not have an end request-response loop, the next () method must be called to give control to the next middleware or the request will be suspended.
The following middleware can be used for Express applications: application-level middleware routing-level middleware error handling middleware built-in middleware third-party middleware
Use the optional mount path to load the middleware at the application level or at the route level. In addition, you can also install a series of middleware functions at the same time to create a sub-middleware stack on a mount point. application-level middleware
App-level middleware binds to app objects using App.use () and apps. Method (), where methods are required to process HTTP requests, such as GET, PUT, POST, and so on, all lowercase. For example:
var app = Express ();
Middleware without Mount path, each request of the application executes the middleware
app.use (function (req, res, next) {
Console.log (' Time: ', Date.now ());
Next ();
});
The middleware attached to/user/:id, any request to/user/:id will execute it
app.use ('/user/:id ', function (req, res, next) {
Console.log (' Request Type: ', req.method);
Next ();
});
The Routing and Handle function (middleware system) that handles the GET request to the/user/:id
app.get ('/user/:id ', function (req, res, next) {
res.send (' user '); c13/>});
The following example shows the loading of a set of middleware at a mount point.
A middleware stack that prints information about any HTTP request that points to/user/:id
app.use ('/user/:id ', function (req, res, next) {
Console.log (' Request URL: ', req.originalurl);
Next ();
}, Function (req, res, next) {
console.log (' Request Type: ', req.method);
Next ();
});
As a routing handle to a middleware system, it makes it possible to define multiple routes for a path. In the following example, two routes are defined for GET requests that point to/user/:id. The second route, while not causing any problems, will never be called because the first route has terminated the request-response loop.
A middleware stack that handles GET requests to/user/:id
app.get ('/user/:id ', function (req, res, next) {
console.log (' ID: ', req.params. ID);
Next ();
}, Function (req, res, next) {
res.send (' User Info ');
});
Process/user/:id, print out User ID
app.get ('/user/:id ', function (req, res, next) {
res.end (req.params.id);
});
If you need to skip the remaining middleware in the middleware stack, call the next (' route ') method to pass control over to the next route. Note: Next (' Route ') only uses the app. VERB () or router. VERB () loaded middleware is valid.
A middleware stack that handles GET requests
to/user/:id app.get ('/user/:id ', function (req, res, next) {
//If the user ID is 0, skip to the next route
if (Req.params.id = = 0) Next (' Route ');
Otherwise the control is given to the next middleware else next in the stack (
);//
}, Function (req, res, next) {
//Render General page
Res.render (' regular ');
});
Processing/user/:id, rendering a special page
app.get ('/user/:id ', function (req, res, next) {
res.render (' Special ');
});
routing-level middleware
Routing-level middleware is just like application-level middleware, except that it binds to express. Router ().
var router = Express. Router ();
The routing level uses router.use () or router. VERB () load.
The above middleware systems created at the application level can be rewritten to the routing level by the following code:
var app = Express ();
var router = Express. Router ();
Middleware with no mount path, each request through that route executes the middleware
router.use (function (req, res, next) {
Console.log (' Time: ', Date.now ());
Next ();
});
A middleware stack that displays information about any HTTP requests that point to/user/:id
router.use ('/user/:id ', function (req, res, next) {
console.log (' request URL: ', req.originalurl);
Next ();
}, Function (req, res, next) {
console.log (' Request Type: ', req.method);
Next ();
});
A middleware stack that handles GET requests
to/user/:id router.get ('/user/:id ', function (req, res, next) {
//If the user ID is 0, skip to the next route
if (req.params.id = = 0) Next (' Route ');
Responsible for handing control over to the next middleware
else next ()
, function (req, res, next) {
//Render General page
Res.render (' regular ');
});
Processing/user/:id, rendering a special page
router.get ('/user/:id ', function (req, res, next) {
console.log (req.params.id);
Res.render (' special ');
});
Mount the route to the application
app.use ('/', router);
Error Handling Middleware
Error-handling middleware has 4 parameters, which must be used when defining error-handling middleware. Even if you do not need a next object, you must declare it in your signature, or the middleware will be recognized as a generic middleware and cannot handle errors.
The error-handling middleware is similar to other middleware definitions, with 4 parameters instead of 3, with the following signatures: (Err, req, res, next).
App.use (function (err, req, res, next) {
console.error (err.stack);
Res.status. Send (' Something broke! ');
});
Please refer to the error handling chapter for more information on error handling middleware. built-in middleware
Starting with the 4.x release, Express is no longer dependent on Connect. In addition to the express.static, the previously built-in middleware for Express is now fully installed and used as a module. Please refer to the middleware list. express.static (root, [options])
Express.static is the only built-in middleware for Express. It is based on serve-static and is responsible for hosting static resources in Express applications.
The parameter root refers to the root directory that provides static resources.
The optional options parameter has the following properties.
Properties |
Description |
type |
Default Value |
dotfiles |
whether to export files with file names beginning with a dot (.). Optional values are "Allow", "Deny" and "Ignore" |
String |
"Ignore" |
etag |
enable ET AG generates |
Boolean |
true |
extensions |
setting file name extension backup options |
Array |
[] |
index |
Send directory index file, set to false disable directory index. |
Mixed |
"index.html" |
lastmodified |
settings last-modified The header is the last modified date of the file on the operating system. The possible values are true or false. |
Boolean |
true |
maxAge |
Set the max-age of the Cache-control header in milliseconds or its string format Property. |
number |
0 |
redirect |
When the path is a directory, redirect to "/". |
Boolean |
true |
setheaders |
Sets the HTTP header to provide a function for the file. |
Function |
|
The following example uses the Express.static middleware, where the options object has been carefully designed.
var options = {
dotfiles: ' Ignore ',
Etag:false,
extensions: [' htm ', ' html '],
index:false,
maxAge : ' 1d ',
redirect:false,
setheaders:function (res, PATH, stat) {
res.set (' X-timestamp ', Date.now ());
}
}
App.use (express.static (' Public ', options));
Each app can have more than one static directory.
App.use (express.static (' public '));
App.use (express.static (' uploads '));
App.use (express.static (' files '));
For more information on serve-static and its parameters, refer to the serve-static documentation. third-party middleware
Add more functionality to Express applications by using third-party middleware.
The node module that installs the required functionality and is loaded in the app, can be loaded at the application level, or at the route level.
The following example installs and loads a middleware that parses cookies: Cookie-parser
$ NPM Install Cookie-parser
var express = require (' Express ');
var app = Express ();
var cookieparser = require (' Cookie-parser ');
Load the middleware
app.use (Cookieparser ()) used to parse cookies;
Refer to the third-party middleware for a list of third-party middleware frequently used in Express.