如何将我的koa路线拆分为单独的文件?

时间:2015-05-17 10:04:14

标签: node.js koa koa-router

我正在试图弄清楚如何将我的路线拆分成单独的文件。

到目前为止,我有这个,但它不起作用。我尝试访问Not found

时收到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;

8 个答案:

答案 0 :(得分:38)

对于任何阅读此内容的人,谁对如何在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

<强>路由/ root.js

import Router from 'koa-router'
const router = new Router()

router.get('/', async (ctx, next) => {
  ctx.body = 'Hello'
})

export default router

<强>路由/ 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

如果您想避免使用routes()allowedMethods()重复,可以使用koa-compose一起组合中间件。为简单起见,我围绕它做了wrapper以简化koa-router的工作。使用它看起来像这样:

<强> app.js

import Koa from 'koa'
import router from './routes'

const app = new Koa()

app.use(router())

export default app  

<强>路由/ index.js

import combineRouters from 'koa-combine-routers'
import rootRouter from './root'
import userRouter from './user'

const router = combineRouters(
  rootRouter,
  userRouter
)

export default router

它会做同样的事情。

答案 1 :(得分:16)

server.js

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

routes.js

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

答案 2 :(得分:11)

这样的事情应该有效:

// 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

答案 3 :(得分:4)

当我做

时,我认为 TJ 的简约方法

koa,koa-route,koa-mount

使用您喜欢的方式安装小型独立应用程序:

<强> 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;

答案 4 :(得分:2)

这就是我最终的目标:

myCompanyLibrary.dockInstance.locator=

答案 5 :(得分:2)

对于Koa 2.x,我发现带有前缀嵌套路线可以交付货物,没有其他包裹。

假设 / api / dogs / api / cats 是必需的结果。

像这样:

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 / catsRou​​ter.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;

答案 6 :(得分:2)

您可以将所有路由放入一个名为routes的文件夹中,然后遍历该文件夹中的所有文件,并要求它们进行初始化。对于任何新路线,只需要在routes文件夹中创建一个文件即可。

是这样的:

index.js

const Koa = require("koa");
const logger = require("koa-logger");
const bodyParser = require("koa-bodyparser");

const app = new Koa();

app.use(logger());
app.use(bodyParser());

require("./routes")(app);

const server = app.listen(config.server.port);

module.exports = server;

/routes/index.js

const fs = require("fs");
const path = require("path");
const baseName = path.basename(module.filename);

const routes = fs
    .readdirSync(path.join(__dirname))
    .filter(
        file =>
            file.indexOf(".") !== 0 &&
            file !== baseName &&
            file.slice(-3) === ".js"
    )
    .map(file => require(path.join(__dirname, file)));

module.exports = function(app) {
    for (var router of routes) {
        app.use(router.routes());
    }
};

然后在您想要的/ routes文件夹中

/routes/user.js

/routes/customer.js

所有路由器出口,例如

/routes/auth.js

const Router = require("koa-router");
const authControllers = require("../controllers/auth");

const {
    jwtAuth,
    login,
    register,
    forgotPassword,
    resetPassword,
    getAuthenticatedUser
} = authControllers;

const router = new Router({ prefix: "/auth" });

router.post("/register", register);
router.post("/login", login);
router.post("/forgot-password", forgotPassword);
router.post("/reset-password/:resetToken", resetPassword);
router.get("/profile", jwtAuth, getAuthenticatedUser);

module.exports = router;

答案 7 :(得分:0)

类似,但正是我需要的:

app.js

"use strict";
import Koa from 'koa';
const app = new Koa();

import Router from 'koa-router';
const router = new Router();

import mount from 'koa-mount';
import routes from "./router/index.mjs";

app.use(mount(routes));
app.use(router.routes());

app.listen(3000, () => console.log("Listening on port: 3000"));

路由器/index.mjs

"use strict";
import Koa from 'koa';
const app = new Koa();

import Router from 'koa-router';
const router = new Router();

router.get('/', async (ctx, next) => {
    ctx.body = {success: true};
    await next();
});

app.use(router.routes());

export default app;