Home>Article>Web Front-end> What is node middleware

What is node middleware

藏色散人
藏色散人 Original
2022-12-29 15:42:16 2963browse

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.

InNodeJS,Middlewaremainly refers to the method of encapsulatinghttprequest details processing. We all know that many actions are often involved inhttprequests, as follows:IP filteringQuery string transferRequest body parsingCookie information processingPermission check VerificationLoggingSession management middleware (session)gzip compression middleware (such as compress) * Error handling

Of course there are many custom processing actions. ForFor Webapplications, 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 introducedNode Middlewareto simplify and encapsulate these basic logic processing details.

node middlewareEssentially, before entering specific business processing, letspecific filtersdeal with. As shown in the figure below:

What is node middleware

The mainstream nodejs frameworks we currently see, such asconnect,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 middlewareImplementation 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 ofnext, 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 thenextfunction. We can package the return value of next intopromise, so that it can be used during business processing. After completion, continue processing the middleware logic through thethencallback. 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对象,实现了其提出的洋葱圈模型,如下图所示:

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

利用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!

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