Node middleware mainly refers to the method of encapsulating http request details. Its essence is to let specific filters process it before entering specific business processing; for Web applications, introducing Node middleware can Simplify and encapsulate some basic logic processing details.
#The operating environment of this tutorial: Windows 10 system, node v12.21.0 version, Dell G3 computer.
What is node middleware?
In-depth introduction to the principle of nodejs middleware
Foreword
Middleware is between application systems and system software It is a type of software that uses the basic services (functions) provided by system software to connect various parts of the application system or different applications on the network, and can achieve the purpose of resource sharing and function sharing.
In NodeJS, Middleware mainly refers to the method of encapsulating http request details processing. We all know that many actions are often involved in http requests, as follows: IP filtering Query string transfer Request body parsing Cookie information processing Permission check Verification Logging Session management middleware (session) gzip compression middleware (such as compress) * Error handling
Of course there are many custom processing actions. For For Web applications, we do not want to understand every detail of the processing work, but hope to focus on business development to achieve the purpose of improving development efficiency, so we introduced Node Middleware to simplify and encapsulate these basic logic processing details.
node middlewareEssentially, before entering specific business processing, let specific filtersdeal with. As shown in the figure below:

The mainstream nodejs frameworks we currently see, such as connect, koa, express, egg, nest, etc. are all inseparable from the design concept of middleware, so in order to give everyone a deeper peek into nodejs In the world, we have comparatively studied the implementation principles of middleware.
Text
After understanding the concept of node middleware, we will manually implement the middleware, and finally we will briefly analyze Let’s take a look at the implementation ideas of middleware in koa. The outline of the article is as follows: Implementation of core principles of node middleware Implementation method of koa middle key* Use the koa middleware mechanism to implement your own koa middleware
node Implementation of the core principles of middleware
From the above introduction, we can see that middleware is the processing logic from the beginning of the http request to the end of the response. It usually needs to process the request and response. When we implement the node middleware mode, we also One issue that needs to be considered is the coexistence of multiple middleware. We need to think about how to automate the execution of multiple middleware. Otherwise, only the first middleware will be executed in the process from request to response, so our basic middleware form As follows:
const middleware = (req, res, next) => {
// 请求处理逻辑 next()}
Next, let’s write a simple case to see how middleware is implemented.
// 定义几个中间间函数const m1 = (req, res, next) => {
console.log('m1 run')
next()}const m2 = (req, res, next) => {
console.log('m2 run')
next()}const m3 = (req, res, next) => {
console.log('m3 run')
next()}// 中间件集合const middlewares = [m1, m2, m3]function useApp (req, res) {
const next = () => {
// 获取第一个中间件 const middleware = middlewares.shift()
if (middleware) {
middleware(req, res, next)
}
}
next()}// 第一次请求流进入useApp()
From the above code It is not difficult for us to discover the role of next, which is to realize the key parameters of automatically calling the middleware chain. The print result is as follows:
m1 runm2 runm3 run
The above is the basic implementation The execution mode of middleware, but we also need to consider asynchronous issues. If the middleware also relies on the support of third-party modules or APIs, such as verification, identification and other services, we need to execute next in the callback of the asynchronous middleware. Ensure the normal call execution sequence, as shown in the following code:
const m2 = (req, res, next) => {
fetch('/xxxxx').then(res => {
next()
})}
There is also a middleware scenario, such as logging middleware, request monitoring middleware, they will be processed before business processing Relevant logic will be executed after processing. At this time, we need to be able to perform secondary processing on the next function. We can package the return value of next into promise, so that it can be used during business processing. After completion, continue processing the middleware logic through the then callback. As shown below:
function useApp (req, res) {
const next = () => {
const middleware = middlewares.shift()
if (middleware) {
// 将返回值包装为Promise对象 return Promise.resolve(middleware(req, res, next))
}else {
return Promise.resolve("end")
}
}
next()}
At this time we can call it in the following way:
const m1 = (req, res, next) => {
console.log('m1 start')
return next().then(() => {
console.log('m1 end')
})}
Above we have implemented a basic middleware design pattern. Of course, we can also use async and await to implement it. The writing method will be more elegant and simple. Here is a simple example from the author:
const m1 = async (req, res, next) => {
// something... let result = await next();
}
const m2 = async (req, res, next) => {
// something... let result = await next();
}
const m3 = async (req, res, next) => {
// something... let result = await next();
return result;
}const middlewares = [m1, m2, m3];function useApp (req, res) {
const next = () => {
const middleware = middlewares.shift()
if (middleware) {
return Promise.resolve(middleware(req, res, next))
}else {
return Promise.resolve("end")
}
}
next()
}// 启动中间件useApp()
在koa2框架中, 中间件的实现方式也是将next()方法返回值封装为Promise对象,实现了其提出的洋葱圈模型,如下图所示:

koa中间件实现方式
koa2框架的中间件实现原理很优雅,笔者觉得很必要研究一下, 这里展示一下其核心思路:
function compose (middleware) {
// 提前判断中间件类型,防止后续错误 if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
// 中间件必须为函数类型 if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
return function (context, next) {
// 采用闭包将索引缓存,来实现调用计数 let index = -1
return dispatch(0)
function dispatch (i) {
// 防止next()方法重复调用 if (i
利用koa中间件机制实现一个自己的koa中间件
学习了中间件的设计机制和原理, 我们是不是想马上写一个中间件呢? 笔者这里给大家举一个例子. 在H5-Dooring项目的服务端代码中, 我们需要对用户登录权限进行分发, 此时我们提供统一个中间件来处理, 如下代码所示:
// 模拟数据库操作const token = db.user();// router或者koa的中间件一定要用await处理next,否则将不能正常响应数据export default async (ctx, next) => {
const t = ctx.request.header.authorization
let uid = ctx.request.header['x-requested-with']
let uidArr = uid.split(',')
if(uidArr.length > 1) {
uid = uidArr.pop().trim()
}
if(token[uid] && token[uid][1] === t) {
await next()
}else {
ctx.status = 403;
ctx.body = {
state: 403,
msg: '你没有权限操作'
}
} }
以上代码即实现用户登录态处理, 如果用户在没有登录的情况下防问任何需要登录的接口, 都将返回权限不足或则在请求库中让其重定向到登录页面.
推荐学习:《node.js视频教程》
The above is the detailed content of What is node middleware. For more information, please follow other related articles on the PHP Chinese website!

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.

React Fragments allow grouping children without extra DOM nodes, enhancing structure, performance, and accessibility. They support keys for efficient list rendering.

The article discusses React's reconciliation process, detailing how it efficiently updates the DOM. Key steps include triggering reconciliation, creating a Virtual DOM, using a diffing algorithm, and applying minimal DOM updates. It also covers perfo


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function