How can I split my koa routes into separate files?

前端 未结 7 1180
一向
一向 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

    Here's what I ended up going with:

    //server.js
    'use strict';
    
    var koa = require('koa');
    var app = koa();
    var serve = require('koa-static');
    var path = require('path');
    var router = require('koa-router');
    var cfg = require('./config');
    var mw = require('./middleware');
    
    app.use(serve(path.resolve(__dirname, '../client')));
    app.use(mw.requestTime('Response-time'));
    app.use(router(app));
    app.use(cfg.db.connect);
    
    require('./routes')(app);
    
    app.get('/api', function *(){
      this.body = 'Welcome to API v1';
    });
    
    app.use(cfg.db.close);
    app.listen(cfg.env.port);
    
    
    
    //routes.js
    module.exports = function (app){
      app.use(require('./api/things').routes());
    };
    
    
    // api/things/index.js
    var Router = require('koa-router');
    
    var router = new Router({
      prefix: '/api/things'
    });
    
    var ctrl = require('./controllers');
    
    router.get('/', ctrl.list);
    router.get('/:id', ctrl.get);
    router.post('/', ctrl.post);
    router.put('/:id', ctrl.put);
    router.del('/:id', ctrl.del);
    
    module.exports = router;
    
    
    // api/things/controllers.js
    
    var r = require('rethinkdb');
    var http = require('http');
    var parse = require('co-body');
    var ctrl = module.exports = {};
    
    ctrl.list = function *(next){
    };
    
    ctrl.get = function *(next){
    };
    
    ctrl.post = function *(next){
    };
    
    ctrl.put = function *(next){
    };
    
    ctrl.del = function *(next){
    };
    

提交回复
热议问题