浅谈Koa2中间件

中间件 与 koa2中间件

通俗的讲:中间件就是匹配路由之前或者匹配路由完成做的一系列的操作,我们就可以 把它叫做中间件。

中间件的作用就是,在上下两个事件通讯的过程中强行塞入一个事件,这个事件可以起到承上启下的作用,并在运行应用的时候做一些只关于部分模块化功能。

中间件其实并不是koa2的发明,在express中就已经存在了,只不过koa2站在了es7巨人的肩膀上,使用async await让中间件形成了一个饱满的洋葱型。

Koa 中间件采用的是洋葱圈模型,每次执行下一个中间件传入两个参数 ctxnext,参数 ctx 是由 koa 传入的封装了 request 和 response 的变量,可以通过它访问 request 和 response,next 就是进入下一个要执行的中间件。

更多精彩内容,请微信搜索“前端爱好者戳我 查看

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

koa2的中间件可以有好几层,在每一次请求与响应的时候,都可以在中间拦截,

做登录态管理、状态码管理、错误处理…总之每个中间件都可以做一次拦截来搞事情。

Koa 中间件作用

中间件功能是可以访问请求对象(request),响应对象(response)和应用程序的请求-响应周期中通过 next 对下一个中间件函数的调用。

通俗来讲,利用这个特性在 next 之前对 request 进行处理,在 next 函数之后对 response 处理。Koa 的中间件模型可以非常方便的实现后置处理逻辑。

实例

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)

输出

1
2
3
2-1
1-1

自己编写一个Koa路由中间件

官网地址: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)

使用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)

参考文档

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

猜你喜欢

转载自blog.csdn.net/BradenHan/article/details/130818435