【nodeJs】koa中间件的基本用法

一、什么是Koa的中间件

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

在express中间件(Middleware) 是一个函数,它可以访问请求对象(request object (req)), 响应对象(response object (res)), 和 web 应用中处理请求-响应循环流程中的中间件,一般被命名为 next 的变量。

中间件的功能包括:

执行任何代码。
修改请求和响应对象。
终结请求-响应循环。
调用堆栈中的下一个中间件。

如果回调函数中,没有next参数,那么匹配上第一个路由,就不会往下匹配了。如果想往下匹配的话,那么需要写next()

二、Koa应用可使用如下几种中间件:

应用级中间件
路由级中间件
错误处理中间件
第三方中间件

1.应用级中间件

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();
app.use(async (ctx,next)=>{
    console.log(new Date());
    await next();
})
router.get('/', function (ctx, next) {
    ctx.body="Hello koa";
})
router.get('/news',(ctx,next)=>{
    ctx.body="news页面"
});
app.use(router.routes()); //作用:启动路由
app.use(router.allowedMethods()); //作用: 当请求出错时的处理逻辑
app.listen(3000,()=>{
    console.log('starting at port 3000');
});

2、路由中间件

router.get('/', async(ctx, next)=>{
    console.log(1)
    next();  //传递给下一个中间件
})
router.get('/', function (ctx) {
    ctx.body="Hello koa";
})

3、错误处理中间件

app.use(async (ctx,next)=> {
    await next();
    if(ctx.status==404){
        ctx.body="这是一个404页面";
    }
});

4、第三方中间件

const static = require('koa-static'); 
const staticPath = './static'; 
app.use(static(path.join( __dirname, staticPath))) 

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

三、Koa中间件的执行顺序

Koa 的中间件和 Express 不同,Koa 选择了洋葱圈模型。 如下图:
这里写图片描述
可以通过一个例子来理解洋葱模型:

const Koa = require('koa');
const app = new Koa();

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


app.use(async (ctx, next) => {    //匹配任何路由的中间件
    console.log('<1');
    next();
    console.log('1>');
})
app.use(async (ctx, next) => {   
    console.log('<2');
    next();
    console.log('2>');
})
app.use(async (ctx, next) => {  
    console.log('<3');
    next();
    console.log('3>');
})

router.get('/', async ctx=> {
    ctx.body = 'hello World';
})

app
  .use(router.routes())  //启动路由
  .use(router.allowedMethods());  //自动帮你设置响应头


app.listen(3000, function () {
    console.log('server start at 3000');
});

请求localhost:3000可以看到控制台的消息:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/AC_greener/article/details/80551171