koa 基础(八)koa 中间件的执行顺序

时间:2023-03-09 13:04:58
koa 基础(八)koa 中间件的执行顺序

1.koa 中间件的执行顺序

app.js

/**
* koa 中间件的执行顺序
*/
// 引入模块
const Koa = require('koa');
const router = require('koa-router')(); /*引入是实例化路由 推荐*/ // 实例化
let app = new Koa(); // Koa中间件
// 匹配任何路由,如果不写next,这个路由被匹配到了就不会继续向下匹配 // www.域名.com/news
app.use(async (ctx, next) => {
console.log('1、这是一个中间件01');
await next(); console.log('5、匹配路由完成以后又会返回来执行中间件');
}) app.use(async (ctx, next) => {
console.log('2、这是一个中间件02');
await next(); console.log('4、匹配路由完成以后又会返回来执行中间件');
}) router.get('/', async (ctx) => {
ctx.body = '首页';
}) router.get('/news', async (ctx) => {
console.log('3、匹配到了news这个路由');
ctx.body = '这是一个新闻页面';
}) router.get('/login', async (ctx) => {
ctx.body = '登录页面';
}) app.use(router.routes());
app.use(router.allowedMethods());
/**
* router.allowedMethods() 作用:这是官方文档的推荐用法,我们可以
* 看到 router.allowedMethods() 用在了路由匹配 router.routes()之后,
* 所以在当所有路由中间件最后调用,此时根据 ctx.status 设置 response 响应头
*/ app.listen(3000);

.