5

I am trying to use Koa.js, and checked out the following modules for routing requests: 1. koa-route 2. koa-mount

When I check their github page/tutorials in google, the examples look almost similar with minor differences.

  1. For koa-route:

    var route = require('koa-route');
    app.use(route.get('/', index));
    
    //functions to handle the request
    function* index(){
        this.body = "this should be home page!";
    }
    
  2. For koa-mount:

     //syntax to add the route
    var mount = require('koa-mount');
    var a = koa();
    app.use(mount('/hello', a));
    
    //functions to handle the request
    a.use(function *(next){
      yield next;
      this.body = 'Hello';
    });
    

The only difference seems to me is mount needs a middleware to serve the request, while route needs a generator to serve the requests.

I am confused when to use what and when to use both(saw that in some tutorials)?

Kop4lyf
  • 4,520
  • 1
  • 25
  • 31

2 Answers2

6

Koa-mount's purpose is to mount one app into another. For example you can create standalone blog app and mount it to another app. You can mount apps others have created too.

Molda
  • 5,619
  • 2
  • 23
  • 39
0

koa-mount - It will mount different koa application into your given route.

const mount = require('koa-mount');
const Koa = require('koa');
// hello
const Hello = new Koa();

Hello.use(async function (ctx, next){
  await next();
  ctx.body = 'Hello';
});

// world

const World = new Koa();

World.use(async function (ctx, next){
  await next();
  ctx.body = 'World';
});

// app
const app = new Koa();

app.use(mount('/hello', Hello));
app.use(mount('/world', World));

app.listen(3000);

console.log('listening on port 3000');

Above example has three different koa applications Hello, World and app. app:3000/hello route mounting koa application Hello and app:3000/world route mounting koa application World. Hello and World are 2 different independent koa application those are mounted to app application.

Koa-route does not work with multiple koa application. It will handle only one application. So Hello and World should be a class/method in app.

    const route = require('koa-route');
    const Koa = require('koa');
    
    const Hello = async (ctx, next) => {
      await next();
      ctx.body = "Hello"
    }
    
    const World = async (ctx, next) => {
      await next();
      ctx.body = "World"
    }
    
    // app
    const app = new Koa();

    app.use(mount('/hello', Hello));
    app.use(mount('/world', World));

    app.listen(3000);

    console.log('listening on port 3000');

Another thing koa-route can handle middleware where koa-mount is used as middleware.