search
HomeWeb Front-endJS TutorialAnalyze express middleware mechanism and its implementation principle

This article mainly introduces the express middleware mechanism and implementation principle. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look

Introduction

The middleware mechanism allows us to add a processing step to a given process, thereby The input or output of this process has an impact, or produces some intermediate effects, states, or intercepts this process. The middleware mechanism is similar to tomcat's filter, both of which are specific implementations of the chain of responsibility model.

express middleware use case


let express = require('express')
let app = express()
//解析request 的body
app.use(bodyParser.json())
//解析 cookie
app.use(cookieParser())
//拦截
app.get('/hello', function (req, res) {
 res.send('Hello World!');
});

Simulate the middleware mechanism and simulate the middle of parsing the request File

First simulate a request


request = { //模拟的request
  requestLine: 'POST /iven_ HTTP/1.1',
  headers: 'Host:www.php.cn\r\nCookie:BAIDUID=E063E9B2690116090FE24E01ACDDF4AD:FG=1;BD_HOME=0',
  requestBody: 'key1=value1&key2=value2&key3=value3',
}

A http request is divided into The request line, request header, and request body are separated by \r\n\r\n, that is, a blank line. It is assumed that the three have been separated, requestLine (request line) contains method type, request url, and http version number. These three are distinguished by spaces. Each part of headers (request header) is separated by \r\n to separate, requestBody (request body) uses & to distinguish parameters

Simulation middleware mechanism

The agreed middleware must be A function that accepts three parameters: request, response, next


function App() {
  if (!(this instanceof App))
    return new App();
  this.init();
}
App.prototype = {
  constructor: App,
  init: function() {
    this.request = { //模拟的request
      requestLine: 'POST /iven_ HTTP/1.1',
      headers: 'Host:www.php.cn\r\nCookie:BAIDUID=E063E9B2690116090FE24E01ACDDF4AD:FG=1;BD_HOME=0',
      requestBody: 'key1=value1&key2=value2&key3=value3',
    };
    this.response = {}; //模拟的response
    this.chain = []; //存放中间件的一个数组
    this.index = 0; //当前执行的中间件在chain中的位置
  },
  use: function(handle) { //这里默认 handle 是函数,并且这里不做判断
    this.chain.push(handle);
  },
  next: function() { //当调用next时执行index所指向的中间件
    if (this.index >= this.chain.length)
      return;
    let middleware = this.chain[this.index];
    this.index++;
    middleware(this.request, this.response, this.next.bind(this));
  },
}

Middleware for request processing


 function lineParser(req, res, next) {
    let items = req.requestLine.split(' ');
    req.methond = items[0];
    req.url = items[1];
    req.version = items[2];
    next(); //执行下一个中间件
  }

function headersParser(req, res, next) {
  let items = req.headers.split('\r\n');
  let header = {}
  for(let i in items) {
    let item = items[i].split(':');
    let key = item[0];
    let value = item[1];
    header[key] = value;
  }
  req.header = header;
  next(); //执行下一个中间件
}

function bodyParser(req, res, next) {
  let bodyStr = req.requestBody;
  let body = {};
  let items = bodyStr.split('&');
  for(let i in items) {
    let item = items[i].split('=');
    let key = item[0];
    let value = item[1];
    body[key] = value;
  }
  req.body = body;
  next(); //执行下一个中间件
}

function middleware3(req, res, next) {
  console.log('url: '+req.url);
  console.log('methond: '+req.methond);
  console.log('version: '+req.version);
  console.log(req.body);
  console.log(req.header);
  next(); //执行下一个中间件
}

Test code


##

let app = App();
app.use(lineParser);
app.use(headersParser);
app.use(bodyParser);
app.use(middleware3);
app.next();

Overall code


function App() {
  if (!(this instanceof App))
    return new App();
  this.init();
}
App.prototype = {
  constructor: App,
  init: function() {
    this.request = { //模拟的request
      requestLine: 'POST /iven_ HTTP/1.1',
      headers: 'Host:www.php.cn\r\nCookie:BAIDUID=E063E9B2690116090FE24E01ACDDF4AD:FG=1;BD_HOME=0',
      requestBody: 'key1=value1&key2=value2&key3=value3',
    };
    this.response = {}; //模拟的response
    this.chain = []; //存放中间件的一个数组
    this.index = 0; //当前执行的中间件在chain中的位置
  },
  use: function(handle) { //这里默认 handle 是函数,并且这里不做判断
    this.chain.push(handle);
  },
  next: function() { //当调用next时执行index所指向的中间件
    if (this.index >= this.chain.length)
      return;
    let middleware = this.chain[this.index];
    this.index++;
    middleware(this.request, this.response, this.next.bind(this));
  },
}
function lineParser(req, res, next) {
    let items = req.requestLine.split(' ');
    req.methond = items[0];
    req.url = items[1];
    req.version = items[2];
    next(); //执行下一个中间件
  }

function headersParser(req, res, next) {
  let items = req.headers.split('\r\n');
  let header = {}
  for(let i in items) {
    let item = items[i].split(':');
    let key = item[0];
    let value = item[1];
    header[key] = value;
  }
  req.header = header;
  next(); //执行下一个中间件
}

function bodyParser(req, res, next) {
  let bodyStr = req.requestBody;
  let body = {};
  let items = bodyStr.split('&');
  for(let i in items) {
    let item = items[i].split('=');
    let key = item[0];
    let value = item[1];
    body[key] = value;
  }
  req.body = body;
  next(); //执行下一个中间件
}

function middleware3(req, res, next) {
  console.log('url: '+req.url);
  console.log('methond: '+req.methond);
  console.log('version: '+req.version);
  console.log(req.body);
  console.log(req.header);
  next(); //执行下一个中间件
}
let app = App();
app.use(lineParser);
app.use(headersParser);
app.use(bodyParser);
app.use(middleware3);
app.next();

Run result

After running the above overall code, the following information will be printed

##

url: /iven_
methond: POST
version: HTTP/1.1
{key1: "value1", key2: "value2", key3: "value3"}
{Host: "www.php.cn", Cookie: "BAIDUID=E063E9B2690116090FE24E01ACDDF4AD"}

The above is the detailed content of Analyze express middleware mechanism and its implementation principle. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
node项目中如何使用express来处理文件的上传node项目中如何使用express来处理文件的上传Mar 28, 2023 pm 07:28 PM

怎么处理文件上传?下面本篇文章给大家介绍一下node项目中如何使用express来处理文件的上传,希望对大家有所帮助!

使用Slim框架中间件实现国际短信发送和接收功能使用Slim框架中间件实现国际短信发送和接收功能Jul 28, 2023 pm 02:48 PM

使用Slim框架中间件实现国际短信发送和接收功能在现代社会中,短信已成为人们日常生活中重要的沟通工具之一。而随着国际交流的增加,国际短信发送和接收功能也日益受到重视。本文将介绍如何使用Slim框架中间件来实现国际短信发送和接收的功能。Slim是一个轻量级的PHP微框架,它提供了简单而强大的路由功能,非常适合用于快速开发小型API应用。同时,Slim也支持使用

深入比较Express和Laravel:如何选择最佳框架?深入比较Express和Laravel:如何选择最佳框架?Mar 09, 2024 pm 01:33 PM

深入比较Express和Laravel:如何选择最佳框架?在选择一个适合自己项目的后端框架时,Express和Laravel无疑是两个备受开发者欢迎的选择。Express是基于Node.js的轻量级框架,而Laravel则是基于PHP的流行框架。本文将深入比较这两个框架的优缺点,并提供具体的代码示例,以帮助开发者选择最适合自己需求的框架。性能和扩展性Expr

Express和Laravel的对比分析:选择更适合你的框架Express和Laravel的对比分析:选择更适合你的框架Mar 10, 2024 pm 10:15 PM

Express和Laravel是两个非常流行的Web框架,分别代表了JavaScript和PHP两大开发语言的优秀框架。本文将针对这两个框架进行对比分析,帮助开发者选择更适合自己项目需求的框架。一、框架简介Express是一个基于Node.js平台的Web应用程序框架,它提供了一系列强大的功能和工具,使开发者可以快速搭建高性能的Web应用程序。Express

CakePHP中间件:快速构建可扩展的Web应用程序CakePHP中间件:快速构建可扩展的Web应用程序Jul 28, 2023 am 11:33 AM

CakePHP中间件:快速构建可扩展的Web应用程序概述:CakePHP是一个流行的PHP框架,被广泛应用于Web应用程序的开发。其提供了许多功能强大的工具和功能,其中包括中间件。中间件可以帮助我们快速构建和扩展Web应用程序,提高代码的可读性和可维护性。什么是中间件:中间件是在请求被派发给控制器之前或之后执行的一系列操作。它们可以完成许多任务,如身份验证、

Laravel中间件:为应用程序添加数据库查询和性能监控Laravel中间件:为应用程序添加数据库查询和性能监控Jul 28, 2023 pm 02:53 PM

Laravel中间件:为应用程序添加数据库查询和性能监控导言:在开发Web应用程序时,数据查询和性能监控是非常重要的。Laravel提供了一种方便的方式来处理这些需求,即中间件。中间件是在请求和响应之间进行处理的一种技术,它可以在请求到达控制器之前或响应返回给用户之后执行一些逻辑。本文将介绍如何使用Laravel中间件来实现数据库查询和性能监控。一、创建中间

Symfony框架中间件:提供错误处理和异常管理功能Symfony框架中间件:提供错误处理和异常管理功能Jul 28, 2023 pm 01:45 PM

Symfony框架中间件:提供错误处理和异常管理功能当我们在开发应用程序时,经常会遇到错误和异常的情况。为了优化用户体验和提供更好的开发者工具,Symfony框架提供了强大的错误处理和异常管理功能。在本文中,我们将介绍Symfony框架中间件的使用和示例代码。Symfony框架中的错误处理和异常管理功能主要通过中间件来实现。中间件是一个特殊的功能组件,用于在

银河麒麟系统安装中间件银河麒麟系统安装中间件Jun 12, 2023 am 11:13 AM

现在越来越多的企业级应用需要运行在国产化环境中,本文介绍下我们产品使用的中间件在国产操作系统银河麒麟的安装(不一定是最优方式,但能用)。包含;Nginx、Redis、RabbitMQ、MongoDB、dotNETCore。下图是银河麒麟服务器的信息:想要顺利安装需要确保:1、服务器能访问网络。想要完全离线的方式安装会更复杂,需要进一步研究。2、修改yum源。使用vi/etc/yum.repos.d/kylin_aarch64.repo来设置yum源,文件内容如下:###KylinLinuxAdv

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!