How can I split my koa routes into separate files?

前端 未结 7 1166
一向
一向 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 05:12


    EDIT: I've updated the code examples below because the koa-router package on npm is no longer maintained. The Koa team has made an official fork of it under the name @koa/router.


    For anyone reading this, who is curious on how to do this in Koa 2.X:

    app.js

    import Koa from 'koa'
    import rootRouter from './routes/root'
    import userRouter from './routes/user'
    
    const app = new Koa()
    
    app.use(rootRouter.routes())
    app.use(rootRouter.allowedMethods())
    app.use(userRouter.routes())
    app.use(userRouter.allowedMethods())
    
    export default app
    

    routes/root.js

    import Router from '@koa/router'
    const router = new Router()
    
    router.get('/', async (ctx, next) => {
      ctx.body = 'Hello'
    })
    
    export default router
    

    routes/user.js

    import Router from '@koa/router'
    const router = new Router({ prefix: '/user' })
    
    router.get('/', async (ctx, next) => {
      ctx.body = 'Some User'
    })
    
    export default router
    

    If you want to avoid the repetition with the routes() and the allowedMethods(), you can use koa-compose to compose the middleware together. For simplicity, I made a wrapper around it to simplify working with koa-router. Using it would look something like this:

    app.js

    import Koa from 'koa'
    import router from './routes'
    
    const app = new Koa()
    
    app.use(router())
    
    export default app  
    

    routes/index.js

    import combineRouters from 'koa-combine-routers'
    import rootRouter from './root'
    import userRouter from './user'
    
    const router = combineRouters(
      rootRouter,
      userRouter
    )
    
    export default router
    

    And it would do the same thing.

提交回复
热议问题