How can I split my koa routes into separate files?

前端 未结 7 1170
一向
一向 2021-01-30 04:20

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

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 04:46

    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;
    

提交回复
热议问题