How can I split my koa routes into separate files?

前端 未结 7 1183
一向
一向 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:06

    Minimalistic approach which i think TJ kept in mind when he did

    koa, koa-route, koa-mount

    Approach with small independent apps which mounted the way you like then:

    index.js

    var app = require('./app')
    app.listen(3000);
    

    app.js

    const Koa = require('koa')
    const _ = require('koa-route')
    const mount = require('koa-mount')
    const app = new Koa()
    const pets = require('./pets')
    
    // sub apps
    app.use(mount('/pets', pets))
    
    // root app
    app.use(_.get('/', function(){
      this.body = "hello";
    }))
    
    module.exports = app;
    

    pets.js

    var Koa = require('koa');
    var _ = require('koa-route');
    var app = new Koa();
    
    
    app.use(_.get('/', ctx => ctx.body = "pets" ));
    app.use(_.get('/:name', (ctx, name) => ctx.body = "pet: "+ name));
    
    module.exports = app;
    

提交回复
热议问题