2

我的koa@next应用程序具有以下结构。我koa-router@next用于路由:

./app.js

const Koa = require('koa');
const router = require('koa-router')();

const index = require('./routes/index');

const app = new Koa();

router.use('/', index.routes(), index.allowedMethods());
app
  .use(router.routes())
  .use(router.allowedMethods());

module.exports = app;

./routes/index.js

const router = require('koa-router')();

router.get('/', (ctx, next) => {
  ctx.body = 'Frontpage';
});

router.get('/hello', (ctx, next) => {
  ctx.body = 'Hello, World!';
});

module.exports = router;

我在路线上遇到Not Found错误。/hello

依赖版本:

"dependencies": {
  "koa": "^2.0.0-alpha.7",
  "koa-router": "^7.0.1",
},

koa-routerv7.1.0 相同。

感谢您的帮助!

4

1 回答 1

1

像这样重构应用程序可以解决问题。我想现在是在精神上抛弃 Express 的时候了。

./app.js

import Koa from 'koa';
import index from './routes/index';

const app = new Koa();

app.use(index.routes(), index.allowedMethods());

export default app;

./routes/index.js

import Router from 'koa-router';

const router = new Router();
//const router = new Router({ prefix: '/subroute' })

router.get('/', (ctx, next) => {
  ctx.body = 'Frontpage';
});

router.get('/hello', (ctx, next) => {
  ctx.body = 'Hello, World!';
});

export default router;
于 2016-11-30T13:12:47.663 回答