Search code examples
javascriptnode.jskoakoa-router

koa-router error router.routes is not a function


When I try to use koa-route 3.2.0 example from their website, I got error message router.routes is not a function

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

const app = new Koa();
app.use(logger());

router.get('/users', (ctx, next) => {
    ctx.response.body =`<h1>Hello!</h1>`;
});

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

// don't listen to this port if the app is required from a test script
if (!module.parent) {
  app.listen(1337);
  console.log('listening on port: 1337');
}

I got error message:

app.use(router.routes())
               ^

TypeError: router.routes is not a function
    at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:40:16)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

When I try to change

const router = require('koa-route');

to

var router = require('koa-router')();

I got error message:

const router = require('koa-route')();
                                   ^

TypeError: require(...) is not a function
    at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:2:36)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

Solution

  • Looks like you've installed the newer version, available at https://github.com/alexmingoia/koa-router/tree/master

    You need to use new Router() instead.

    Also looks like you're mixing up koa-router with koa-route, which are two different packages.

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