子路由不能在单独的文件中使用 koa-router
Sub-routes not working in separate file with koa-router
我的 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;
我在 /hello
路线上遇到 Not Found
错误。
依赖版本:
"dependencies": {
"koa": "^2.0.0-alpha.7",
"koa-router": "^7.0.1",
},
同koa-router
v7.1.0.
感谢您的帮助!
像这样重组应用程序解决了问题。我想是时候在精神上放弃 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;
我的 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;
我在 /hello
路线上遇到 Not Found
错误。
依赖版本:
"dependencies": {
"koa": "^2.0.0-alpha.7",
"koa-router": "^7.0.1",
},
同koa-router
v7.1.0.
感谢您的帮助!
像这样重组应用程序解决了问题。我想是时候在精神上放弃 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;