preface
Recent learning, before using Express framework to write the server did not pay attention to middleware what! It was not until the interviewer told me that you had told me about middleware that I realized that I had not studied it properly! This time, follow the official framework instructions, while recording, summarize the Express framework in the middle ~ ~
Express[1] is a routing and middleware Web framework that has minimal functionality on its own: An Express application is basically a series of middleware function calls.
The middleware function can access the request object [2] (REQ), the response object [3] (RES), and the next middleware function in the application’s request/response loop. The next middleware function is usually represented by a variable named next.
Example:
// Generic middleware
function middleware(req, res, next) {
// Intermediate processing logic.....
next();
}
// req is the request, res is the response and next is the call to the next middleware function Copy the code
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and response objects.
- End the request/response loop.
- Call the next middleware function in the stack.
If the above request/response loop does not end after the current middleware completes execution, the middleware must call the next() function to give control of the request to the next middleware. Otherwise, the request remains pending.
The Express framework can be divided into the following categories according to the different use modes of middleware:
- Application layer middleware
- Router layer middleware
- Error handling middleware
- Built-in middleware
- Third-party middleware
Application layer middleware
Middleware can bind to instances of application objects using the app.use() and app.method () functions. Middleware can be defined internally or externally in a method, but only by reference in the above two methods. METHOD refers to the HTTP METHOD in lower case on the request.
Middleware functions, subsequent examples are based on the following examples:
const express = require('express');
const app = express();
function middleware(req, res, next) {
console.log('The request comes... ');
next(); } Copy the code
1. App.use () method binding
Middleware functions with no installation path. This function is executed each time the application receives a request.
app.use(middleware);
Copy the code
Middleware functions installed in the /user/:id path. Execute this function in the /user/: ID path for any type of HTTP request.
app.use('/user/:id', middleware)
Copy the code
The above middleware notation is defined externally, but it can also be defined internally as follows:
app.use('/user/:id', (req, res, next) => {
console.log(req.params.id);
res.send(req.params.id)
})
Copy the code
2. App.method () method binding
This is a common approach that we use to handle a particular request.
app.get('/user/:id', (req, res, next) => {
console.log(req.params.id);
res.send(req.params.id)
})
Copy the code
3. Summary
Multiple middleware
The following is an example of using the installation path to load a set of middleware functions at the installation point. As soon as one of them ends the request/response loop, the call to the middleware substack stops.
app.use('/user/:id', middleware, middleware2 ...)
Copy the code
Jumping call
You can call next(‘route’) to pass control to the next route. Suitable for scenarios where you want to skip the remaining middleware functions in the router middleware stack.
Note: Next (‘route’) is only valid in middleware functions loaded with app.method () or router.method () functions.
Second, router layer middleware
Router layer middleware works in much the same way as application layer middleware, except that it binds to instances of express.Router().
var app = express();
var router = express.Router();
// Routing middleware processing logic...
// Hang in the routing middleware to the application instance app.use('/', router); Copy the code
Load router layer middleware with router.use() and router.method () functions. Similar to the above application layer middleware usage:
Middleware with no installed path executes this middleware for each request:
router.use(function (req, res, next) {
console.log('Time:'.Date.now());
next();
});
Copy the code
The path is defined and the middleware substack is called to handle the request:
router.get('/user/:id'.function (req, res, next) {
// Skip to the next route if the user ID is 0
if (req.params.id == 0) next('route');
// Otherwise, control passes to the next middleware in the substack
else next();
}, function (req, res, next) { // Render the page res.render('regular'); }); Copy the code
Error handling middleware
Error handling differs from other middleware functions in that it has four arguments (Err, REq, RES, next) :
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke! ');
});
Copy the code
4. Built-in middleware
The only built-in middleware function in Express is express.static, which provides static resources for Express applications.
app.use(express.static(rootDir, options));
Copy the code
Where rootDir is the root directory that provides static resources, options is an optional object that can have the following properties:
Reference code:
app.use(express.static('public', {
dotfiles: 'ignore'. etag: false. extensions: ['htm'.'html']. index: false. maxAge: '1d'. redirect: false. setHeaders: function (res, path, stat) { res.set('x-timestamp'.Date.now()); })); Copy the code
Fifth, third-party middleware
In addition to custom and built-in middleware, some third-party middleware will certainly be used to add functionality to Express applications during development.
Common third party plug-ins include body-parser, Compression, cookie-parser, cookie-session, etc.
To use third-party middleware, install node.js modules with the required functionality and then add them to the application layer or router layer applications.
Example of installing cookie-Parser middleware:
$ npm install cookie-parser
Copy the code
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
// load the cookie-parsing middleware app.use(cookieParser()); Copy the code
summary
The essence of middleware is a function that does some of the work for us in the process of receiving the request and returning the response while the server processes the request. Each middleware gives the next middleware control over the request.
The resources
[1]
Express: https://expressjs.com/zh-cn/
[2]
Request object: https://expressjs.com/zh-cn/4x/api.html#req
[3]
Response object: https://expressjs.com/zh-cn/4x/api.html#res
This article was first published on the public account: Dagog’s number