中间件 与 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)

输入

1232-11-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