Table of Contents
Text
node Implementation of the core principles of middleware
koa中间件实现方式
利用koa中间件机制实现一个自己的koa中间件
Home Web Front-end Front-end Q&A What is node middleware

What is node middleware

Dec 29, 2022 pm 03:42 PM
node middleware

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.

What is node middleware

#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:

What is node middleware

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()}
Copy after login

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()
Copy after login

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
Copy after login

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()
  })}
Copy after login

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()}
Copy after login

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')
  })}
Copy after login

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()
Copy after login

在koa2框架中, 中间件的实现方式也是将next()方法返回值封装为Promise对象,实现了其提出的洋葱圈模型,如下图所示:

What is node middleware

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 
Copy after login

利用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: '你没有权限操作'
        }
    }  }
Copy after login

以上代码即实现用户登录态处理, 如果用户在没有登录的情况下防问任何需要登录的接口, 都将返回权限不足或则在请求库中让其重定向到登录页面.

推荐学习:《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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

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

What is the principle of tomcat middleware What is the principle of tomcat middleware Dec 27, 2023 pm 04:40 PM

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 handle form validation using middleware in Laravel How to handle form validation using middleware in Laravel Nov 02, 2023 pm 03:57 PM

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.

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

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 data acceleration in Laravel How to use middleware for data acceleration in Laravel Nov 02, 2023 am 09:40 AM

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 transformation in Laravel How to use middleware for response transformation in Laravel Nov 03, 2023 am 09:57 AM

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

How to use middleware for data recovery in Laravel How to use middleware for data recovery in Laravel Nov 02, 2023 pm 02:12 PM

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?

How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework How to use middleware to set up cross-domain resource sharing (CORS) in the Slim framework Jul 30, 2023 pm 08:34 PM

How to set up Cross-Origin Resource Sharing (CORS) using middleware in the Slim framework Cross-Origin Resource Sharing (CORS) is a mechanism that allows the server to set some additional information in the HTTP response header to tell the browser whether Allow cross-domain requests. In some projects with front-end and back-end separation, the CORS mechanism can be used to realize the front-end's cross-domain request for the back-end interface. When using the Slim framework to develop REST API, we can use middleware (Middleware)

See all articles