Node Express learning and chatting about middleware
This article will take you through the Express middleware in node, and introduce the concept and middleware classification. I hope it will be helpful to everyone!
Express is a simple and flexible web application development framework that can be used to quickly build a fully functional web application; as a tool based on Node. The upper-layer service framework encapsulated by js, Express provides a simpler API, making the organization and management of applications easier through middleware and routing.
The concept of middleware
Middleware is a number of sub-processing functions after modularizing the request processing function. A series of sub-processing functions can form a middleware Stack;
Middleware is a function that can access the request object req, response object res and next() function in the request-response cycle of the application. The next() function is mainly responsible for passing control to the next middleware; if the current middleware does not terminate the request and next() is not called, the request will be suspended and the middleware defined later will not be executed. ,
The execution order of middleware is strictly in accordance with the registration order from top to bottom.
Middleware function can perform the following tasks:
- Execute any code
- Modify the request and response objects
- End the request-response cycle
- The next middleware in the call stack (next)
The main purpose of middleware is to process HTTP requests. Complete specific tasks such as login status verification, request logs, error handling, cookies, etc.
Middleware classification
1 Application-level middleware
Use the app.use() function to Application-level middleware is bound to the application object instance
const app = express(); /*表示匹配任何路由*/ app.use(function(req,res,next){ console.log('请求时间:' + Date.now()); /*表示匹配完成这个中间件就继续往下执行。*/ next() })
2 Route-level middleware
Route-level middleware works in the same way as application-level middleware , just it is bound to the router instance
import express from 'express'; const app = express(); const router = express.router(); router.use( '/user', function (req, res, next) { console.log(1); next(); }, function (req, res, next) { console.log(2); next(); }, function (rex, res, next) { console.log(3); next(); } );
3 Error handling middleware
Error handling middleware always requires 4 parameters, 4 parameters must be provided to identify it as an error handling middleware function. Even if the next function is not required, it must be specified. Otherwise the next function is interpreted as a regular middleware and the error cannot be handled
app.use(function(err, req, res, next){ console.log(err.stack); res.status(500).send(err); })
4 Built-in middleware
Express has the following built-in middleware:
- express.static: Provides static resource services
- express.router: Provides routing services
##5 Third-party middleware
Third-party middleware such as body-parser, cookie-parser, etc.6 Custom middleware
Custom middleware is defined as a function, accepting req, res ,next parameter, use app.use() to register middlewarefunction log(req,res,next) { req.requestTime = Date.now(); next() } // 注册自定义中间件 app.use(log);
// 自定义可配置中间件 function log(options) { return function (req,res,next) { // 根据options实现中间件功能 next } }
nodejs tutorial! !
The above is the detailed content of Node Express learning and chatting about middleware. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

The principle of tomcat middleware is implemented based on Java Servlet and Java EE specifications. As a Servlet container, Tomcat is responsible for processing HTTP requests and responses and providing the running environment for Web applications. The principles of Tomcat middleware mainly involve: 1. Container model; 2. Component architecture; 3. Servlet processing mechanism; 4. Event listening and filters; 5. Configuration management; 6. Security; 7. Clustering and load balancing; 8. Connector technology; 9. Embedded mode, etc.

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

How to use middleware for data acceleration in Laravel Introduction: When developing web applications using the Laravel framework, data acceleration is the key to improving application performance. Middleware is an important feature provided by Laravel that handles requests before they reach the controller or before the response is returned. This article will focus on how to use middleware to achieve data acceleration in Laravel and provide specific code examples. 1. What is middleware? Middleware is a mechanism in the Laravel framework. It is used

How to use middleware for response conversion in Laravel Middleware is one of the very powerful and practical features in the Laravel framework. It allows us to process requests and responses before the request enters the controller or before the response is sent to the client. In this article, I will demonstrate how to use middleware for response transformation in Laravel. Before starting, make sure you have Laravel installed and a new project created. Now we will follow these steps: Create a new middleware Open

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to use middleware for scheduled task scheduling in Laravel Introduction: Laravel is a popular PHP open source framework that provides convenient and powerful tools to develop web applications. One of the important features is scheduled tasks, which allows developers to run specific tasks at specified intervals. In this article, we will introduce how to use middleware to implement Laravel's scheduled task scheduling, and provide specific code examples. Environment Preparation Before starting, we need to make sure

Laravel is a popular PHP web application framework that provides many fast and easy ways to build efficient, secure and scalable web applications. When developing Laravel applications, we often need to consider the issue of data recovery, that is, how to recover data and ensure the normal operation of the application in the event of data loss or damage. In this article, we will introduce how to use Laravel middleware to implement data recovery functions and provide specific code examples. 1. What is Lara?
