Koa2 first example

1. KOA2 Introduction

  • Web server framework  based on Node.js platform
  • Created by the original team of  Express
  • Express Koa and Koa2 are both web server frameworks . The difference and relationship between them can be shown in the following table

Onion model middleware
As shown in the figure below , for the server, it is actually to process one request after another. After the web server receives one request after another from the browser, it forms one response after another and returns to the browser. And the request It needs to be processed by the program to reach our server. After the program is processed, a response will be formed and returned to the browser. The program that our server processes the request is called middleware in the world of Koa2

There may be more than one such middleware, and there may be more than one. For example, as shown in the figure above, it has three layers of middleware. The process of processing requests and the order in which these three layers of middleware are called are:

When a request arrives at our server, the first layer of middleware that processes the request

After the first-tier middleware processes the request, he will pass the request to the second-tier middleware

After the second-tier middleware processes the request, he will pass the request to the third-tier middleware

There is no middleware inside the third-level middleware, so after the third-level middleware has processed all the code, the request will reach the second-level middleware again, so the second-level middleware has passed through two requests for this request. Second treatment

This call sequence is the onion model . The middleware has a first-in-last-out feeling for request processing. The request first reaches the first layer of middleware, and finally the first layer of middleware processes the request again.

2. Quick start of KOA2

Switch to the directory you want to create, first check the version of Node

node -v

The use of koa2 requires Node version to be above 7.6

Install koa2

npm init -y
这个命令可以快速的创建出package.json的文件,这个文件可以维护项目中的第三方包的信息
npm install koa
这个命令可以在线的联网下载最新版本koa到当前项目中,由于线上最新版本的koa就是koa2,所以我们不需要执行npm install koa2

Write the entry file app.js

//1.创建koa对象
const Koa = require('koa') //导入构造方法
const app = new koa() //通过构造方法,创建实例对象
//2.编写响应函数(中间件)
//ctx:上下文,指的是所处于的web容器,我们可以通过ctx.request拿到请求对象,也可以通过ctx.response拿到响应对象
//next 内层中间件执行的入口
app.use((ctx,next)=>{
  console.log(ctx.request.url)
  ctx.response.body = 'hello world'
})
//3.指明端口号
app.listen(3000)

Start the server

node app.js

So the first instance of koa2 is complete! ! !

Open the browser and enter 127.0.0.1:3000 to access
 

Guess you like

Origin blog.csdn.net/SSbandianH/article/details/112915560