1. What is Koa?

A background framework based on NodeJS. To put it bluntly, it is a javascript language needs to write library, it is positioned as a server application to provide services, itself exposed some API, but also integrate better ideas.

2) The emergence of Koa

First of all, I understand that KOA is definitely not designed to replace some of the existing old background language frameworks, because NodeJS itself has some shortcomings and a large and long history of the old background language, it is not realistic to replace, we can only say that each has its own strengths, complement each other and provide services in collaboration is correct.

3. Real project background

The company recently launched a new project, I also take this to summarize. First of all, the underlying services and personnel configuration of the company are allocated by Java standards, and the application itself is also related to higher standards such as payment and reliability and security, but the back-end architecture provides services externally in the form of micro-services.

Faced a problem at this time, large amount of information such as the front page of the page, to display the data is more dispersed, need more services to provide interface, then led to the front involves multiple HTTP requests a page, because the backend under micro service, without a proper service to undertake the function of the aggregate data, and for the front end, The user experience problems caused by the overhead of many HTTP requests cannot be ignored, and an aggregation business layer is needed to take over.

The purpose of this layer is also very clear, which is to process the underlying data to the front-end layer, but this involves the problem of who will do this layer, of course, any back-end framework that can provide services can do this layer, and for students who have the underlying services to provide attention to this layer is not too nutritious. At this time, front-end students can use their own javascript skills, using nodeJS backend framework to undertake this layer, such as the above mentioned KOA framework is very suitable.

However, there is also a problem, because the reliability required by the project is high, and javascript itself is weak language type and nodeJS single process itself is fragile, so we position the middle layer provided by NodeJS as encapsulating only the query class interface. The operation interfaces involved, such as submission, are still provided by the original underlying business system. In this way, the underlying services themselves are perfectly combined with the newly added aggregation layer services to provide services through mutual cooperation.

Here is a simple architecture diagram for your reference:


4. Benefits of the Koa middle tier

1. Language advantage: Koa is based on javascript development, which is a big benefit because it makes it easier for front-end users to get started.

2. Efficiency improvement: it is convenient for me to complete the adjustment independently when adjusting data on my own page, instead of communicating with other teams at the bottom of efficiency.

3. Aggregation: Back-end microservice system is bound to have the problem of multiple data providers. If multiple HTTP requests are made, user experience may deteriorate, so aggregation of business data is also very important.

4. Broaden their field of vision: general front-end engineer is not very good understanding of the technical architecture and business model, after joining this layer, the front end from the page to the interface layer, can stand to a higher position to see what you have to do, such as some of the data flow link way, still can widen its own technology, gradually become a technology all-around player.


5. Technical model of Koa

Koa’s obvious advantage over the older NodeJS framework Express is its “onion ring” model, because it uses ES6’s generate generator function internally. Koa2 uses ES7’s Async syntax directly, which makes it easier to handle asynchronous writing and avoid ugly callback hell. The other is its powerful plug-in middleware capability, which is very extensible and can be customized with request processing modules, and there are many contributed middleware modules available in the community.


6. Koa Starting Example

Here is a simple example of using Koa to set up a service 🌰

â‘  To achieve goals:

  • Provides HTTP and HTTPS services

  • Query third-party interface services and provide JSON interface to the front end

NVM use 8 NPM I --save koaCopy the code

â‘¡ Directory structure:

â‘¢ Implementation code:

const http = require('http');
const https = require('https');
const Koa = require('koa');
const fs = require('fs');
const axios = require('axios');

const app = new Koa();
app.use(async (ctx, next) => {  
  const now = Date.now();  
  await next();  
  console.log('path: %s cost time is ', ctx.path, Date.now() - now);
});
app.use(async ctx => {  
  const ipInfo = await axios.get('http://ip.taobao.com/service/getIpInfo.php?ip=0.0.0.0');  
  ctx.body = ipInfo.data;
});
http.createServer(app.callback()).listen(3000, () = > {console.log('http server start! ')});let options = { 
  key: fs.readFileSync(__dirname+'/ssl/server.key'),  
  cert: fs.readFileSync(__dirname+'/ssl/server.crt')}; https.createServer(options, app.callback()).listen(443, () = > {console.log('https server start! ')});Copy the code

Note: server.key and server. CRT above are for test use, you need to apply for Tencent cloud or Ali cloud to apply for available certificate.

â‘£ Test example:

The HTTP service:



HTTPS service :(if no valid certificate is available, select ignore security in the browser.)

Interested students strongly recommend to copy the code to the local debugging observation. There is a need for students can see here the use of a koa demo:https://github.com/FantasyGao/koa2 wrote before.


The above content is their own summary, there will be mistakes or understanding bias, if there are questions, I hope you leave a message to correct, so as not to mistake people, if there are any questions please leave a message, we will try our best to answer it. Don’t forget to share it with your friends or give a “like” if it helps! You can also pay attention to the author’s official account, view historical articles and pay attention to the latest developments, to help you become a full stack engineer!