


Compare the differences and connections between express and koa middleware patterns
This article mainly introduces the detailed comparison between express and koa middleware modes. 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 and take a look.
Cause
I’ve recently been learning how to use koa. Since koa is a fairly basic web framework, a complete web application is Most of the required things are introduced in the form of middleware, such as koa-router, koa-view, etc. It is mentioned in the koa documentation: koa's middleware model is different from express's. koa is an onion type, express is a linear type. As for why this is the case, many articles on the Internet do not specifically analyze it. Or simply put, it is the characteristics of async/await. Let’s not talk about whether this statement is right or wrong. For me, this statement is still too vague. So I decided to analyze the similarities and differences in the principles and usage of the two middleware implementations through the source code.
For the sake of simplicity, express here is replaced by connect (the implementation principle is the same)
Usage
Both are based on the official website (github) document Subject to
connect
The following is the usage on the official website:
var connect = require('connect'); var http = require('http'); var app = connect(); // gzip/deflate outgoing responses var compression = require('compression'); app.use(compression()); // store session state in browser cookie var cookieSession = require('cookie-session'); app.use(cookieSession({ keys: ['secret1', 'secret2'] })); // parse urlencoded request bodies into req.body var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: false})); // respond to all requests app.use(function(req, res){ res.end('Hello from Connect!\n'); }); //create node.js http server and listen on port http.createServer(app).listen(3000);
According to the document we can see, connect provides a simple routing function:
app.use('/foo', function fooMiddleware(req, res, next) { // req.url starts with "/foo" next(); }); app.use('/bar', function barMiddleware(req, res, next) { // req.url starts with "/bar" next(); });
The middleware of connect is linear. After next, continue to search for the next middleware. This mode is also intuitively good. Understand that middleware is a series of arrays, and the processing method for finding corresponding routes through route matching is middleware. In fact, connect is also implemented in this way.
app.use is to insert new middleware into the middleware array. The execution of middleware relies on the private method app.handle for processing, and the same principle applies to express.
koa
Compared with connect, koa’s middleware model is not so intuitive. Let’s use the diagram on the Internet to express it:
That is, koa will come back after processing the middleware, which gives us more room for operation. Let’s take a look at koa’s official website example:
const Koa = require('koa'); const app = new Koa(); // x-response-time app.use(async (ctx, next) => { const start = Date.now(); await next(); const ms = Date.now() - start; ctx.set('X-Response-Time', `${ms}ms`); }); // logger app.use(async (ctx, next) => { const start = Date.now(); await next(); const ms = Date.now() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}`); }); // response app.use(async ctx => { ctx.body = 'Hello World'; }); app.listen(3000);
Obviously, when koa processing middleware encounters await next(), it will pause the current middleware and process the next middleware, and finally go back to continue processing the remaining tasks. Although it is very complicated to say, But intuitively we have a vaguely familiar feeling: isn't it just a callback function? Let’s not talk about the specific implementation method here, but it is indeed a callback function. It has nothing to do with the features of async/await.
Source code brief analysis
The core difference between connect and koa middleware mode lies in the implementation of next. Let us briefly look at the implementation of next between the two.
connect
The source code of connect is quite small and only contains 200 lines of comments. It seems very clear that the connect middleware processing lies in the private method proto.handle. , the same next is also implemented here
// 中间件索引 var index = 0 function next(err) { // 递增 var layer = stack[index++]; // 交由其他部分处理 if (!layer) { defer(done, err); return; } // route data var path = parseUrl(req).pathname || '/'; var route = layer.route; // 递归 // skip this layer if the route doesn't match if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) { return next(err); } // call the layer handle call(layer.handle, route, err, req, res, next); }
After deleting the obfuscated code, we can see that the next implementation is also very simple. A recursive call sequence looking for middleware. Keep calling next. The code is quite simple but the idea is worth learning.
Where done is the third-party processing method. Other parts dealing with sub apps and routing have been deleted. Not the point
koa
koa separates the implementation of next into a separate package. The code is simpler, but it implements a seemingly more complex function
function compose (middleware) { return function (context, next) { // last called middleware # let index = -1 return dispatch(0) function dispatch (i) { index = i try { return Promise.resolve(fn(context, function next () { return dispatch(i + 1) })) } catch (err) { return Promise.reject(err) } } } }
Looking at the code processed above, some students may still be confused.
Then let’s continue processing:
function compose (middleware) { return function (context, next) { // last called middleware # let index = -1 return dispatch(0) function dispatch (i) { index = i let fn = middleware[i] if (i === middleware.length) { fn = next } if (!fn) return return fn(context, function next () { return dispatch(i + 1) }) } } }
In this way, the program is simpler and has nothing to do with async/await. Let’s take a look at the results. Okay
var ms = [ function foo (ctx, next) { console.log('foo1') next() console.log('foo2') }, function bar (ctx, next) { console.log('bar1') next() console.log('bar2') }, function qux (ctx, next) { console.log('qux1') next() console.log('qux2') } ] compose(ms)()
Execute the above program and we can find the output in sequence:
foo1
bar1
qux1
qux2
bar2
foo2
is also the so-called onion model of koa. At this point we can draw the conclusion that koa's middleware model has no actual connection with async or generator, but koa emphasizes async takes precedence. The so-called middleware pause is only due to the callback function (in my opinion, there is no difference between promise.then and callback, and even async/await is also a form of callback).
The above is the detailed content of Compare the differences and connections between express and koa middleware patterns. 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

In today's smartphone market, consumers are faced with more and more choices. With the continuous development of technology, mobile phone manufacturers have launched more and more models and styles, among which Vivox100 and Vivox100Pro are undoubtedly two products that have attracted much attention. Both mobile phones come from the well-known brand Vivox, but they have certain differences in functions, performance and price. So when facing these two mobile phones, which one is more worth buying? There are obvious differences in appearance design between Vivox100 and Vivox100Pro

Currently, the potential coins that are favored by the currency circle include SOL coin and BCH coin. SOL is the native token of the Solana blockchain platform. BCH is the token of the BitcoinCash project, which is a fork currency of Bitcoin. Because they have different technical characteristics, application scenarios and development directions, it is difficult for investors to make a choice between the two. I want to analyze which one has more potential, SOL currency or BCH? Invest again. However, the comparison of currencies requires a comprehensive analysis based on the market, development prospects, project strength, etc. Next, the editor will tell you in detail. Which one has more potential, SOL coin or BCH? In comparison, SOL coin has more potential. Determining which one has more potential, SOL coin or BCH, is a complicated issue because it depends on many factors.

Windows 10 vs. Windows 11 performance comparison: Which one is better? With the continuous development and advancement of technology, operating systems are constantly updated and upgraded. As one of the world's largest operating system developers, Microsoft's Windows series of operating systems have always attracted much attention from users. In 2021, Microsoft released the Windows 11 operating system, which triggered widespread discussion and attention. So, what is the difference in performance between Windows 10 and Windows 11? Which

TV boxes, as an important device that connects the Internet and TV, have become more and more popular in recent years. With the popularity of smart TVs, consumers are increasingly favoring TV box brands such as Tmall, Xiaomi, ZTE and Huawei. In order to help readers choose the TV box that best suits them, this article will provide an in-depth comparison of the features and advantages of these four TV boxes. 1. Huawei TV Box: The smart audio-visual experience is excellent and can provide a smooth viewing experience. Huawei TV Box has a powerful processor and high-definition picture quality. Such as online video, and built-in rich applications, music and games, etc., it supports a variety of audio and video formats. Huawei TV box also has voice control function, which makes operation more convenient. You can easily cast the content on your mobile phone to the TV screen. Its one-click casting

Title: Performance comparison, advantages and disadvantages of Go language and other programming languages. With the continuous development of computer technology, the choice of programming language is becoming more and more critical, among which performance is an important consideration. This article will take the Go language as an example to compare its performance with other common programming languages and analyze their respective advantages and disadvantages. 1. Overview of Go language Go language is an open source programming language developed by Google. It has the characteristics of fast compilation, efficient concurrency, conciseness and easy readability. It is suitable for the development of network services, distributed systems, cloud computing and other fields. Go

Comparative evaluation of Vivox100 and Vivox100Pro: Which one do you prefer? As smartphones continue to become more popular and more powerful, people's demand for mobile phone accessories is also growing. As an indispensable part of mobile phone accessories, headphones play an important role in people's daily life and work. Among many headphone brands, Vivox100 and Vivox100Pro are two products that have attracted much attention. Today, we will conduct a detailed comparative evaluation of these two headphones to see their advantages and disadvantages

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.
