I\'m trying to figure out how to split my routes into separate files.
I have this so far, but it doesn\'t work. I just get Not found
when I try to access
For Koa 2.x I find nested routes with prefixes to deliver the goods, with no additional packages.
Assuming /api/dogs and /api/cats are the required outcomes.
Like so:
app.js
import Koa from 'koa';
import Router from 'koa-router';
import apiRouter from './routes/apiRouter';
const app = new Koa();
app.use(apiRouter.routes(), apiRouter.allowedMethods());
app.listen(3000);
export default app;
routes/apiRouter.js
import Router from 'koa-router'
import dogsRouter from './dogsRouter'
import catsRouter from './catsRouter'
const apiRouter = new Router({ prefix: '/api' })
const nestedRoutes = [dogsRouter, catsRouter]
for (var router of nestedRoutes) {
apiRouter.use(router.routes(), router.allowedMethods())
}
export default apiRouter;
routes/dogsRouter.js
import Router from 'koa-router'
const dogsRouter = new Router({ prefix: '/dogs' });
dogsRouter.get('/', async (ctx, next) => {
ctx.body = 'Dogs be here'
});
export default dogsRouter;
routes/catsRouter.js
import Router from 'koa-router'
const catsRouter = new Router({ prefix: '/cats' });
catsRouter.get('/', async (ctx, next) => {
ctx.body = 'Cats be here'
});
export default catsRouter;