Getting Started with koa Quick Start

install koa2

npm install koa@2

 

hello koa2 code

// Import koa, which is different from koa 1.x. In koa2, we import a class, so it is represented by uppercase Koa: 
const Koa = require('koa' );

// Create a Koa object to represent the web app itself: 
const app = new Koa();

// For any request, the app will call this asynchronous function to handle the request: 
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});

// Listen on port 3000: 
app.listen(3000 );
console.log('app started at port 3000...');

For each http request, koa will call the async function we pass in to handle:

async (ctx, next) => {
    await next();
    // Set the Content-Type of the response: 
    ctx.response.type = 'text/html' ;
     // Set the content of the response: 
    ctx.response.body = '<h1>Hello, koa2!</h1>' ;
}

Among them, the parameter ctx is passed in by koa to encapsulate the variables of request and response, through which we can access request and response, next is the next asynchronous function passed in by koa to be processed.

 

start demo

Since koa2 is based on async/await operation middleware, it can only be used in the harmony mode of node.js 7.x, so the script at startup is as follows:

node index.js

 

koa middleware middleware

Middleware is something like a filter, a method between the client and the application that handles requests and responses.

.middleware1 {
  // (1) do some stuff
  .middleware2 {
    // (2) do some other stuff
    .middleware3 {
      // (3) NO next yield !
      // this.body = 'hello world'
    }
    // (4) do some other stuff later
  }
  // (5) do some stuff lastest and return
}

The execution of middleware is very similar to an onion, but it is not executed layer by layer, but is demarcated by next. The part before next in this layer is executed first. After the execution of the next layer of middleware, the next layer of this layer is executed. later part.

let koa = require ('koa' );
let app = new koa ();

app.use((ctx, next) => {
  console.log(1)
  next(); // If next is not written, an error will be reported 
  console.log(5 )
});

app.use((ctx, next) => {
  console.log(2)
  next();
  console.log(4)
});

app.use((ctx, next) => {
  console.log(3)
  ctx.body = 'Hello World';
});

app.listen( 3000 );
 // print out 1 , 2, 3, 4, 5

The above simple application prints out 1, 2, 3, 4, and 5. This is actually the core of koa middleware control, an onion structure, which comes in layer by layer from top to bottom, and then goes back layer by layer from bottom to top. , at first glance is very complicated, why not just go down one layer at a time and end it, just like express/connect, we just go to the next middleware as long as next, why come back?

In fact, this is a cascading code designed to solve frequent callbacks in complex applications. It does not directly hand over the control to the next middleware, but goes to the next middleware when it encounters the next. will execute the following content

What is the basis for solving frequent callbacks? For a simple example, if we need to know the time passing through the middleware, we can easily write it using koa, but when using express, we can look at the source code of express response-time, it can only be detected by listening to the header. When writing out, the callback function is triggered to calculate the time, but koa does not need to write callback at all, we only need to add a few lines of code after next to solve it

Every time an http request is received, koa will call the async function registered through app.use() and pass in the ctx and next parameters.

We can operate on ctx and set the return content. But why call await next()?

The reason is that koa combines many async functions into a processing chain, each async function can do some things of its own, and then use await next() to call the next async function. We call each async function middleware, and these middleware can be combined to complete many useful functions.

For example, you can use the following three middleware to form a processing chain, print logs in sequence, record processing time, and output HTML:

app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`); // print URL 
    await next(); // call next middleware 
});

app.use(async (ctx, next) => {
    const start = new Date().getTime(); // current time 
    await next(); // call the next middleware 
    const ms = new Date ().getTime() - start; //console.log 
    (` Time: ${ms}ms`); // Printing takes time });


app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});

The order of middleware is very important, that is, the order of calling app.use() determines the order of middleware.

Also, what happens if a middleware doesn't call await next()? The answer is that subsequent middleware will no longer be executed. This situation is also common, for example, a middleware that detects user permissions can decide whether to continue processing the request, or simply return a 403 error:

app.use(async (ctx, next) => {
    if (await checkUserPermission(ctx)) {
        await next();
    } else {
        ctx.response.status = 403;
    }
});

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325220671&siteId=291194637