Search code examples
node.jskoakoa-router

Sub-routes not working in separate file with koa-router


My koa@next app have the following structure. I'm using koa-router@next for the routing:

./app.js

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

const index = require('./routes/index');

const app = new Koa();

router.use('/', index.routes(), index.allowedMethods());
app
  .use(router.routes())
  .use(router.allowedMethods());

module.exports = app;

./routes/index.js

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

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

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

module.exports = router;

I'm getting Not Found error on the /hello route.

Dependency versions:

"dependencies": {
  "koa": "^2.0.0-alpha.7",
  "koa-router": "^7.0.1",
},

It's the same with koa-router v7.1.0.

Thank You for your help!


Solution

  • Restructuring the app like this solves the problem. I guess it's just really time to ditch Express mentally.

    ./app.js

    import Koa from 'koa';
    import index from './routes/index';
    
    const app = new Koa();
    
    app.use(index.routes(), index.allowedMethods());
    
    export default app;
    

    ./routes/index.js

    import Router from 'koa-router';
    
    const router = new Router();
    //const router = new Router({ prefix: '/subroute' })
    
    router.get('/', (ctx, next) => {
      ctx.body = 'Frontpage';
    });
    
    router.get('/hello', (ctx, next) => {
      ctx.body = 'Hello, World!';
    });
    
    export default router;