visual usando tutorial subir studio proyecto node cómo crear archivos node.js koa koa-router

node.js - usando - ¿Cómo puedo dividir mis rutas koa en archivos separados?



npm (5)

server.js

var app = require(''koa'')(); var router = require(''./routes''); app.use(router.routes()); app.use(router.allowedMethods()); app.listen(3000);

rutas.js

var router = require(''koa-router'')(); router.get(''/'', function* () { this.body = ''router test''; }); module.exports = router;

Estoy tratando de averiguar cómo dividir mis rutas en archivos separados.

Tengo esto hasta ahora, pero no funciona. Me acabo de encontrar Not found cuando intento acceder a http://localhost:3001/api/things

//server.js var koa = require(''koa''); var app = koa(); var router = require(''koa-router''); app.use(router(app)); require(''./routes'')(app); // routes.js module.exports = function *(app){ app.use(''/api/things'', require(''./api/things'')); }; // api/things/index.js var Router = require(''koa-router''); var router = new Router({ prefix: ''/api/things'' }); router.get(''/'', function *(){ this.body = [{ name: ''Foo''}, { name: ''Bar'' }]; }); module.exports = router;


Algo como esto debería funcionar:

// app.js var koa = require(''koa''), app = koa(); require(''./routes1'')(app); require(''./routes2'')(app); app.listen(3000); // routes1.js var Router = require(''koa-router''); function register (app) { var router = new Router({ prefix: ''/api'' }); router.get(''/'', ...); // responds to "/api" router.get(''/messages'', ...); // responds to "/api/messages" app.use(router.routes()); app.use(router.allowedMethods()); } module.exports = register // routes2.js var Router = require(''koa-router''); function register (app) { var router = new Router(); router.get(''/'', ...); // responds to "/" app.use(router.routes()); app.use(router.allowedMethods()); } module.exports = register


Enfoque minimalista que creo que TJ tuvo en cuenta cuando lo hizo

koa, koa-ruta, koa-mount

Enfoque con pequeñas aplicaciones independientes que se montan de la manera que más te guste:

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;

mascotas.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;


Esto es lo que terminé yendo con:

//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){ };


Para cualquiera que lea esto, que tenga curiosidad sobre cómo hacerlo en 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

rutas / root.js

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

rutas / usuario.js

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

Si desea evitar la repetición con las routes() y los allowedMethods() , puede usar koa-compose para componer el middleware juntos. Para simplificar, hice una wrapper alrededor de él para simplificar el trabajo con koa-router . Usándolo se vería algo como esto:

app.js

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

rutas / index.js

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

Y haría lo mismo.