Talking about Koa2 middleware

Middleware and koa2 middleware

In layman's terms: middleware is a series of operations performed before or after matching routes, we can call it middleware.

The role of middleware is to force an event into the process of communication between the upper and lower events . This event can serve as a link between the previous and the next , and do some modular functions only when running the application.

Middleware is not actually an invention of koa2, it already exists in express, but koa2 stands on the shoulders of es7 giants, using async await to make the middleware form a full onion shape.

The Koa middleware adopts the onion ring model. Each time the next middleware is executed, two parameters ctx and next are passed in. The parameter ctx is a variable that encapsulates the request and response passed in by koa, and the request and response can be accessed through it. next is to enter the next middleware to be executed.

For more exciting content, please search for " " on WeChat前端爱好者 , and click me to view .

// 中间件,暴露一个函数
module.exports = function () {
  return async function (ctx, next) {
    pv(ctx);
    // 执行下一个中间件,没有下一个中间件就执行完了
    await next();
  };
};

The middleware of koa2 can have several layers, and it can be intercepted in the middle of each request and response.

Do login status management, status code management, error handling... In short, every middleware can do an interception to do things.

Koa middleware role

The middleware function can access the request object (request), the response object (response) and the call to the next middleware function through next in the request-response cycle of the application.

Generally speaking, use this feature to process the request before next, and process the response after the next function. Koa's middleware model can be very convenient to implement post-processing logic.

example

const koa = require('koa')

const app = new koa()

app.use(async (ctx,next) => {
    console.log('1')
    await next()
    console.log('1-1')
    ctx.body = 'hello world'
})

app.use(async (ctx,next) => {
    console.log('2')
    await next()
    console.log('2-1')
})

app.use((ctx) => {
    console.log('3')
})

app.listen(3000)

output

1
2
3
2-1
1-1

Write a Koa routing middleware yourself

Official website address : https://koa.bootcss.com/index.html#request

const koa = require('koa')

const app = new koa()

app.use(async (ctx) => {
    if (ctx.url === '/') {
        console.log('这是首页');
        ctx.body = '这是首页'
    } else if (ctx.url === '/user') {
        if (ctx.method === 'GET') {
            console.log('这是用户列表页');
            ctx.body = '这是用户列表页'
        } else if (ctx.method === 'POST') {
            console.log('添加用户');
            ctx.body = '添加用户'
        }
    } else {
        ctx.status = 404
    }
})

app.listen(3000)

Implement routing with koa-router

const koa = require('koa')
const Router = require('koa-router')
const app = new koa()

const router = Router({
	prefix: '/user'
})

router.get('/', async (ctx) => {
	ctx.body = '这是用户首页'
})

router.get('/del', async (ctx) => {
	ctx.body = '删除用户'
})

router.post('/add', async (ctx) => {
	ctx.body = '添加用户'
})

app.use(router.routes())

app.listen(3000)

reference documents

  • https://koa.bootcss.com/index.html

Guess you like

Origin blog.csdn.net/BradenHan/article/details/130818435