Exploring the Powerful Functionalities of Koa Router for Efficient Route Handling in Koa.js

Introduction to Koa Router

Koa Router is a powerful and elegant routing middleware for Koa.js, which helps you to manage various routes in your Koa application efficiently. In this article, we will explore numerous useful APIs provided by Koa Router and also showcase a complete application example utilizing these APIs.

Basic Usage

 const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router();
router.get('/', (ctx, next) => {
  ctx.body = 'Hello World';
  next();
});
app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen(3000); 

Route Parameters

 router.get('/users/:id', (ctx, next) => {
  const userId = ctx.params.id;
  ctx.body = `User ID: ${userId}`;
  next();
}); 

Named Routes

 router.get('user', '/users/:id', (ctx, next) => {
  ctx.body = `User ID: ${ctx.params.id}`;
  next();
});
console.log(router.url('user', 3));  // Output: /users/3 

Route Middleware

 router.post('/users', async (ctx, next) => {
  ctx.body = 'User created';
  await next();
}); 

Multiple Middleware for a Single Route

 router.get('/info', 
  async (ctx, next) => {
    console.log('First middleware');
    await next();
  },
  async (ctx, next) => {
    ctx.body = 'Information Page';
    await next();
  }
); 

Handling 405 Method Not Allowed

 app.use(router.routes()); app.use(router.allowedMethods({
  throw: true,
  notImplemented: () => Boom.notImplemented(),  // Example using Boom for handling
  methodNotAllowed: () => Boom.methodNotAllowed()
})); 

Router Prefix

 const adminRouter = new Router({
  prefix: '/admin'
});
adminRouter.get('/dashboard', (ctx, next) => {
  ctx.body = 'Admin Dashboard';
  next();
});
app
  .use(adminRouter.routes())
  .use(adminRouter.allowedMethods());

Composing Multiple Routers

 const productRouter = new Router(); productRouter.get('/products', (ctx, next) => {
  ctx.body = 'Product List';
  next();
});
const categoryRouter = new Router(); categoryRouter.get('/categories', (ctx, next) => {
  ctx.body = 'Category List';
  next();
});
app
  .use(productRouter.routes())
  .use(categoryRouter.routes())
  .use(productRouter.allowedMethods())
  .use(categoryRouter.allowedMethods());

Complete App Example

 const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); const productRouter = new Router({ prefix: '/products' });
router.get('/', (ctx, next) => {
  ctx.body = 'Welcome to Koa Application';
  next();
});
productRouter.get('/', (ctx, next) => {
  ctx.body = 'Product List';
  next();
});
productRouter.get('/:id', (ctx, next) => {
  ctx.body = `Product ID: ${ctx.params.id}`;
  next();
});
app
  .use(router.routes())
  .use(router.allowedMethods())
  .use(productRouter.routes())
  .use(productRouter.allowedMethods());

app.listen(3000, () => {
  console.log('Server is running on port 3000');
}); 

By utilizing Koa Router, you can efficiently manage routing in your Koa.js applications, making your development process smoother and more organized.

Hash: 83f0ccdc2064a87b8438a5e7870c6f500d819b93144d1d150a59795106166e1c

Leave a Reply

Your email address will not be published. Required fields are marked *