Middleware
Framework Koa.js Route Middleware
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
// middleware function for all routes
const globalMiddleware = async (ctx, next) => {
console.log('Global middleware');
await next();
}
// middleware function for users route
const usersMiddleware = async (ctx, next) => {
console.log('Users middleware');
await next();
}
// define routes
router.get('/users', usersMiddleware, async (ctx, next) => {
ctx.body = 'User list';
});
router.get('/posts', async (ctx, next) => {
ctx.body = 'Post list';
});
// print all route settings
console.log('Current route settings:');
router.stack.forEach((layer) => {
console.log(`Route: ${layer.path}`);
layer.stack.forEach((middleware) => {
console.log(`Middleware name: ${middleware.name || 'anonymous'}`);
console.log(`Middleware source code: ${middleware.toString()}`);
});
});
app.use(globalMiddleware);
app.use(router.routes());
app.listen(3000);
Current route settings:
===========
Route: /users
Middleware name: usersMiddleware
Middleware source code: async (ctx, next) => {
console.log('Users middleware');
await next();
}
Middleware name: anonymous
===========
Route: /posts
Middleware name: anonymous
Framework Koa.js Route Middleware