In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to use koa2, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Introduction
Koa is a new web framework built by the people behind Express to become a smaller, more expressive, and more robust cornerstone in the field of web applications and API development. By using the async function, Koa helps you discard the callback function and powerfully enhance error handling. Instead of bundling any middleware, Koa provides an elegant way to help you write server-side applications quickly and happily.
Since it is a web framework, we must be familiar with it. By launching a node http server and listening on a port, we can access our service locally through a similar localhost:3000. This service can be a web website, a restful interface, a static file service, and so on.
Hello Word
There are Hello Word examples in any language or framework to express its simplest getting started Demo, as follows
When we visit the browser localhost:3000, we will see that the Hello Word is printed out, and a koa-based service is started.
Context
The first step in understanding koa is to understand the role of context
For example, someone in the WeChat group said it was snowing outside, but what you saw was a clear sky when you ran to the window. Only then did you realize that it was also October, he was in the cold north, and you were in the hot south.
Similarly, a request will contain the user's login status, or some information such as Token, which is part of the context and is used to determine the context of the request.
Koa's Context encapsulates node's request and response objects into a single object, and provides many useful methods for developing web applications and APIs. Those that operate very frequently in HTTP server development are implemented directly in Koa, rather than in higher-level frameworks, so that middleware does not have to repeat these common functions.
Middle ware
Let's start with an official example:
To explain simply, the code initializes a koa instance. The following three middleware methods are loaded through the use method in the order of execution:
Enter the first middleware next (), skip to the next middleware new Data (), record the current time, next (), skip to the next middleware, skip the ctx.body assignment back to the previous middleware, record the current time again and calculate the time difference, save it to http header and go back to the previous middleware to print out the X-Response-time in header.
The execution sequence here extends the very classic onion model.
It passes through the same middleware twice during a request, allowing us to deal with the logic of different request phases.
Source code parsing
The above introduces the two most important concepts in koa. Let's take a look at how koa works and how the so-called onion model is built.
The lib directory of koa source code is very simple.
Lib |-application.js |-context.js |-request.js |-response.js
Application class initialization
The entry file is application.js. Let's start here.
Application is a class. This class inherits node's Events, which is not expanded in detail here, but initializes the following in constructor:
Proxy Agent is not enabled by default
Middleware middleware is an empty array. Here's the key point.
Env judges according to the environment variable NODE_ENV
Context, request and response import the corresponding files under the lib directory into the current context of this through the Object.create method respectively, and do not pollute the incoming object
Use method
In the normal coding order, after initializing the koa instance (that is, const app = new Koa ()), we need to call app.use () to mount our middleware, so let's see what the use method does
Judge the middleware is function, judge whether the middleware is generator function type, just simply put the middleware function push into the middleware array.
Do you have an uppercase WHAT in mind at this time?
As a matter of fact, it is so straightforward, and there is no complicated logic. As you may have guessed later, the method in middleware is called in a loop to execute. It has not been shown here how the onion model came from. Let's not expand it and continue to execute it in code order.
Listen method
In the normal coding order, after use our middleware is app.listen (3000)
Let's take a look at what this listen did.
The http.createServer here is the way node natively starts the http service. Here, the basics are slightly extended. This method accepts two parameters.
Options [IncomingMessage, ServerResponse] is supported only after node version v9.6.0 and v8.12.0. I will not repeat it here.
RequestListener this parameter is of function type. Two parameters, req and res, are passed in each request.
It is not difficult to understand that the this.callback () method here must have returned a function and received two parameters (req and res). Let's take a look at the source code.
The amount of information in this callback is a bit large, the code itself is not difficult to understand, and the comments are explained, which are explained from top to bottom.
Compose method
The compose method here is mainly responsible for generating the onion model, which is implemented through the koa-compose package. The source code is as follows
You can see the general logic from the comments, and the ingenuity here is fn (context, dispatch.bind (null, I + 1)).
This dispatch.bind (null, I + 1) is the second parameter next that we usually write to middleware.
What we get when we execute this next () method is actually the execution of the next middleware.
It is not difficult to understand why when we await next (), we wait for all the subsequent middleware to be executed in series, and it becomes clear when we look back at the execution sequence of the middleware section above.
CreateContext method
For the expansion explanation in callback, take a look at what const ctx = this.createContext (req, res) has done
Here, req, res, this.request and this.response are all mounted on context, and the circular reference hierarchy is sorted out through assignment to provide convenience for users.
HandleRequest method
Or the unfolding explanation in callback, take a look at what this.handleRequest (ctx, fn) has done
Get the onion models generated by ctx and compose respectively and start consuming middleware one by one.
Context.js file
The overall framework is sorted out above. Let's take a look at the internal details of context.js. There are two large segments of agents at the end of the file.
Here you can see all the req and res method collections, so which methods are readable, which are writable, which are both readable and writable, and which methods are not allowed to be modified
This is what the delegates library does.
Delegates internally uses the _ _ defineGetter__ and _ _ defineSetter__ methods to control reading and writing. Of course, we can learn from them, and we can't follow them blindly.
The two api search on MDN will give the same warning message.
This feature is deprecated in favor of defining setters using the object initializer syntax or the Object.defineProperty () API.
In fact, it is recommended that we use Object.defineProperty (), the proxy method of vue, but this library has not been updated for four years and is still running steadily, which is recognized by koa developers.
Other
Request.js and response.js files have nothing to say, but the specific tools and methods to implement, easy for developers to call, interested can read their own source code.
Application
The overall node services of Zhaopin front-end architecture are based on koa implementation, including our vue server rendering and node restful api and so on.
The reason why we choose koa is that it is lightweight, scalable, supports async and await asynchronism, and completely gets rid of callback hell.
There are also mature koa2-based enterprise solutions on the market, such as eggjs and thinkjs.
The above is all the contents of this article "how to use koa2". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.