Koa2 definition

Koa implements a very expressive HTTP middleware framework through Node.js that aims to make Web application development and API usage more enjoyable. Koa’s middleware executes within the stack in coded order, allowing you to perform operations and deliver requests downstream, then filter and return upstream in reverse order.

Almost all methods common to HTTP servers are directly integrated into Koa’s codebase of about a thousand lines of source code. These include content negotiation, normalization of node inconsistencies, redirection, and so on.

Koa does not bundle any middleware.

The characteristics of

The biggest difference between KOA2 and KOA1 is that koA2 implements async/await, while KOA1 implements async/ yield,

Koa2 middleware

Koa is a middleware framework that can be implemented in two different ways:

  • Async Function (currently selected)
  • common function
Use (async (CTX, next)=>{// ### async (CTX, next)=>{//... Await next() // wait for the next middleware to finish before running the next middleware code //... })Copy the code
// middleware usually takes two arguments (CTX, next), CTX is the context of a request, and // next is the function that calls the downstream middleware. Return a promise.app. use((CTX, next) => {const start = date.now (); return next().then(() => { const ms = Date.now() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); }); });Copy the code

1.ctx

Each middleware receives a Koa Context object that encapsulates an incoming HTTP message and responds to the message accordingly. CTX is usually used as the parameter name of the context object.

Request object of ctx. req-node.

Response object of ctx. res-node.

Response processing bypassing Koa is not supported. Avoid using the following Node attributes:

  • res.statusCode
  • res.writeHead()
  • res.write()
  • res.end()

Ctx. request Request object of the KOA.

Ctx. response KoA’s response object.

ctx.body = ctx.res.body = ctx.response.body

2.next()

When one middleware calls next(), the function pauses and passes control to the next middleware defined. When there are no more middleware executions downstream, the stack expands and each middleware resumes performing its upstream behavior.

For front-end developers, the process can be interpreted in two ways:

The first kind of

  • Capture phase  next();Any code before that
  • The target stageReach its targetcontroller
  • Bubbling phase next();Any code after that

The second type of middleware forms a middle stack and executes in a “first-in-last-out” order.

We use async functions as middleware – the following screenshots show the specific project flow