Enhance Your Koa.js Application with koa-router for Efficient Routing

Introduction to koa-router

Koa-router is a powerful and elegant routing middleware for Koa.js, a popular Node.js web framework designed to be smaller, more expressive, and more robust. With koa-router, you can handle routing for your Koa applications easily and efficiently.

API Examples

1. Basic Routing

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

    const app = new Koa();
    const router = new Router();

    router.get('/', (ctx, next) => {
      ctx.body = 'Hello, Koa!';
    });

    app
      .use(router.routes())
      .use(router.allowedMethods());

    app.listen(3000);
  

2. Route Parameters

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

3. Query Parameters

  
    router.get('/search', (ctx, next) => {
      const query = ctx.query.q;
      ctx.body = `Search query: ${query}`;
    });
  

4. Post Requests

  
    router.post('/users', (ctx, next) => {
      const newUser = ctx.request.body;
      ctx.body = `Created user: ${JSON.stringify(newUser)}`;
    });
  

5. Middleware

  
    router.get('/protected', (ctx, next) => {
      if (ctx.headers['authorization']) {
        next();
      } else {
        ctx.status = 401;
      }
    }, (ctx, next) => {
      ctx.body = 'Protected resource';
    });
  

6. Nested Routes

  
    const userRouter = new Router();

    userRouter.get('/', (ctx, next) => {
      ctx.body = 'User list';
    });

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

    router.use('/users', userRouter.routes(), userRouter.allowedMethods());
  

7. Redirects

  
    router.get('/old-route', (ctx) => {
      ctx.redirect('/new-route');
    });

    router.get('/new-route', (ctx) => {
      ctx.body = 'This is the new route';
    });
  

Comprehensive Application Example

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

    const app = new Koa();
    const router = new Router();

    // Basic route
    router.get('/', (ctx) => {
      ctx.body = 'Welcome to Koa.js with koa-router!';
    });

    // Nested routes
    const userRouter = new Router();

    userRouter.get('/', (ctx) => {
      ctx.body = 'List of users';
    });

    userRouter.get('/:id', (ctx) => {
      ctx.body = `User ID: ${ctx.params.id}`;
    });

    router.use('/users', userRouter.routes(), userRouter.allowedMethods());

    // Middleware and protected routes
    router.get('/private', async (ctx, next) => {
      if (ctx.headers['authorization']) {
        await next();
      } else {
        ctx.status = 401;
        ctx.body = 'Unauthorized';
      }
    }, (ctx) => {
      ctx.body = 'Welcome to the private area!';
    });

    app
      .use(bodyParser())
      .use(router.routes())
      .use(router.allowedMethods());

    app.listen(3000, () => {
      console.log('Server running on http://localhost:3000');
    });
  

With the examples provided above, you can quickly and easily implement routing in your Koa.js application using koa-router. It offers flexibility and convenience to handle various routing requirements effortlessly.

Hash: 83f0ccdc2064a87b8438a5e7870c6f500d819b93144d1d150a59795106166e1c

Leave a Reply

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