Know the new | koa framework introduction to proficiency Chapter 1

introduce

koa is based on node JS platform.
It is built by the original team of Express and is committed to becoming a smaller and more expressive web framework.
Writing web applications with koa can avoid the nesting of repeated callback functions and greatly improve the efficiency of error handling,
The koa framework can not only bind any Middleware in the kernel method, but also provide a lightweight and elegant function library. The idea is quite different from that of express.

Installation of koa frame

Install koa

Installing the koa framework is the same as the module before installation.
Use the following command to install

npm install --save koa

Using the save parameter indicates that the package JSON file. Automatically add dependencies

hello world

Enter the following code to run hello world

const koa = require("koa");
const app = new koa();


// Configuring Middleware
app.use(async (ctx) => {
    ctx.body = "hello world";
})

// Listening port
app.listen(3000);

Run file

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js


The output results are as follows

Asynchronous processing

Because js is single threaded, we use callback functions to handle asynchronous problems.

Callback function processing

const koa = require("koa");
const app = new koa();


function getData(callback){
    setTimeout(function () {
        var name = "ming";
        callback(name);
    }, 1000)
}

// Get the data in the asynchronous method from the outside
getData(function (data) {
    console.log(data)
})

// Listening port
app.listen(3000);

Output results

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

Handling asynchrony with promise

const koa = require("koa");
const app = new koa();


// promise handles asynchrony
// resolve successful callback function
// reject failed callback function

var p = new Promise(function (resolve, reject) {
    setTimeout(function () {
        var name = "wolf";
    }, 1000)
})

// Get asynchronous results
p.then((data) => {
    console.log(data);
}) 

// Listening port
app.listen(3000);

The operation results are as follows

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

About async await promise

Async is the abbreviation of async, await is the abbreviation of async wait, so async is used to declare a function as asynchronous, and await is used to wait for the execution of an asynchronous method.

Simple understanding

async makes methods asynchronous
await waits for the asynchronous method execution to complete.

async

Practical examples

Here we use practical examples for better understanding.

Synchronization function

function getData(){
	return "ming";
}
console,log(getData())

Output results

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming

async can make this method asynchronous

const koa = require("koa");
const app = new koa();


// promise handles asynchrony
// resolve successful callback function
// reject failed callback function

async function getData(){
    return "This is a data";
}

console.log(getData());

// Listening port
app.listen(3000);

The output results are as follows

promise is an asynchronous data

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
Promise { 'This is a data' }

Get this data

const koa = require("koa");
const app = new koa();


// promise handles asynchrony
// resolve successful callback function
// reject failed callback function

async function getData(){
    return "This is a data";
}

var p = getData();

p.then((data) => {
    console.log(data);
})

// Listening port
app.listen(3000);

The output result is as shown in the figure

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
 This is a data

await

Obtain asynchronous information using await method

const koa = require("koa");
const app = new koa();


// promise handles asynchrony
// resolve successful callback function
// reject failed callback function

async function getData(){
    return "This is a data";
}

async  function test(){
    // At this time, the running is. It is found that this function is an asynchronous function. When await is encountered, it enters the waiting state. Wait for the execution of getData, and then proceed to the next execution
    var d = await  getData();

    console.log(d)
}

test()

// Listening port
app.listen(3000);

Running results

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
 This is a data

koa routing

Routing is to load different pages to achieve different functions according to different url addresses.

Install routing

 npm install --save koa-router

Use routing

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", (ctx, next) => {
    ctx.body = "ming";
})

// Start routing
app.use(router.routes());
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

The operation results are as follows

You can add async as an asynchronous method to call

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {
    ctx.body = "ming";
})

// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Get linked parameter values

Get the parameter value of the route through the router
Link as

Get formatted

http://localhost:3000/?ming=3

Code is

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.query)

    ctx.body = "ming";
})

// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

The result of the visit is

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
[Object: null prototype] { ming: '3' }

Get unformatted

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
ming=3

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


router.get("/", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.querystring)

    ctx.body = "ming";
})

// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Set dynamic routing

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// Configure dynamic routing
router.get("/:id", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.params)

    ctx.body = "ming";
})

// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

The link visited is

http://localhost:3000/ming

Output content

PS C:\Users\Administrator\IdeaProjects\untitled3> node ./ming.js
{ id: 'ming' }

koa Middleware

The middleware of koa is configured here
Middleware is a series of operations performed by matching routes. It is called middleware.

The functions of middleware mainly include:

  1. Execute any code
  2. Modify request and response objects
  3. End request, response cycle
  4. The next Middleware in the call stack.

Requirement: print out middleware related content

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// middleware 
app.use(async (ctx) => {
    ctx.body = "This is a middleware";
})


// Configure dynamic routing
router.get("/:id", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.params)

    ctx.body = "ming";
})



// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Running results

[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-erhikkny-1594813455965)( https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_758be669b72a1ca132c7aea9629a4cf0.jpg )]The

At this time, this content will appear when you visit any page,

Persistent matching

Because next is not added during access, the route matching phase cannot be entered.

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// middleware 
app.use(async (ctx, next) => {
    ctx.body = "This is a middleware";

    // Enter route matching
    next();
})


// Configure dynamic routing
router.get("/:id", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.params)

    ctx.body = "ming";
})



// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Since js is single threaded, you need to add await for access.

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// middleware 
app.use(async (ctx, next) => {
    ctx.body = "This is a middleware";

    // Enter route matching
    await next();
})


// Configure dynamic routing
router.get("/:id", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.params)

    ctx.body = "ming";
})



// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Route persistent matching

Since there is no await next for the route, the route will no longer match after matching. Therefore, adding next can complete the matching of two identical routes in order.

const koa = require("koa");
const app = new koa();
const router = require("koa-router")();


// middleware 
app.use(async (ctx, next) => {
    ctx.body = "This is a middleware";

    // Enter route matching
    await next();
})


// Configure dynamic routing
router.get("/:id", async (ctx, next) => {

    // query returns a formatted parameter object
    // querystring returns the requested string

    console.log(ctx.params)

    ctx.body = "ming";
    
    await next();
})
router.get("/:id", async (ctx, next) => {
    // Match to this point
    await  next();
})



// Start routing
app.use(router.routes());
// Set response header
app.use(router.allowedMethods());


// Listening port
app.listen(3000);

Execution sequence of Middleware

Generally, the onion model is used as the execution sequence of the middleware.

Error handling Middleware

// middleware 
app.use(async (ctx, next) => {
    console.log("This is a middleware");
    
    // Into the onion
    next()
    
    // Onion out
    if(ctx.status = 404){
        ctx.status = 404;
        ctx.body = "This is a 404 page";
    }
})

Third party Middleware

For example, third-party middleware is used for static file hosting

const static = require('koa-static');
const staticPath = './static';

app.use(static(
	path.join(__dirname, staticPath);
))

const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

This completes static file hosting

Tags: Front-end MongoDB

Posted by phpmady on Mon, 30 May 2022 11:42:14 +0530