node in koa2

Creating koa2 project

First, we create a directory hello-koaand project directory as open with VS Code. Then, we create app.js, enter the following code:

// Import KOA, koa 1.x and different in koa2, we introduced a class, and therefore are indicated in uppercase Koa: 
const = Koa the require ( 'koa2' ); 

// Create object represents a web app itself Koa : 
const app = new new Koa (); 

// for any request, the processing request app asynchronous function calls: 
app.use (the async (CTX, Next) => { 
    the await Next (); 
    ctx.response.type = 'text / HTML ' ; 
    ctx.response.body =' <h1 of> the Hello, koa2 </ h1 of> '! ; 
}); 

// port monitor 3000: 
app.listen (3000 ); 
the console.log ( ' aT port App Started 3000 ... ' );
 // can be accessed at http://127.0.0.1:3000

For every http request, koa will call our function to handle incoming asynchronous:

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

Wherein, the parameter ctxis passed koa encapsulates the request and response variables, we can access it through a request and response, nextit is next passed koa asynchronous function to be processed.

The above asynchronous function, we first used await next();the next processing an asynchronous function, then, provided the response Content-Type and Content.

The asyncfunction is called asynchronous marker function in an asynchronous function in , you can awaitcall another asynchronous function, which will introduce two keywords in ES7.

Liao teacher koa2 official website also explores how this package installed, but now koa2 have been embedded in the node, without additional npm install, here ignored, with the introduction require to use directly in the project.

koa middleware (koa core code middleware)

Let's take a closer look at the implementation logic of koa. The core code is:

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

Each received a http request, koa invoked by app.use()async registered function, passing ctxand nextparameters.

We can ctxoperate and set the return content. But why callawait next() ?

The reason is koa put a lot of async functions that make up a processing chain , each async function can do some of their own things , and then await next()to call the next async function. We each async function called middleware , the middleware can be combined to perform many useful functions.

For example, middleware may be composed of the following three processing chain, sequentially printing log recording processing time, the output HTML:

app.use (the async (CTX, Next) => { 
    the console.log (ctx.request.method `$ {} {$` ctx.request.url}); // print the URL 
    the await Next (); // the call a Middleware 
}); 

app.use (the async (CTX, next) => { 
    const Start = new new a Date () the getTime ();. // this time 
    the await next (); // call the next Middleware 
    const MS = new new a Date () .getTime () - Start; // time consuming 
    the console.log ( `time: $ {} ms` MS); // print time consuming 
}); 

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

order of middleware is very important, which is calling app.use()sequence determines the order of middleware.

In addition, if a middleware does not call await next(), how would you do? The answer is the follow-up of middleware will not be executed. This situation is very common, for example, to detect a user permissions middleware can decide whether to continue processing the request, or direct returns a 403 error:

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

Understand middleware, we will already have used the koa!

Finally, note that ctxobject has a number of shorthand methods, such as ctx.urlequivalent ctx.request.url, ctx.typeequivalent ctx.response.type.

 

Guess you like

Origin www.cnblogs.com/fqh123/p/11032741.html