问题描述
我正在尝试找出如何将路线分成单独的文件.
I'm trying to figure out how to split my routes into separate files.
到目前为止,我已经知道了,但是不起作用.当我尝试访问http://localhost:3001/api/things
I have this so far, but it doesn't work. I just get Not found
when I try to access 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;
推荐答案
编辑:我已经更新了以下代码示例,因为npm上的koa-router
软件包已不再维护. Koa团队已将其正式命名为@koa/router
.
EDIT: I've updated the code examples below because the koa-router
package on npm is no longer maintained. The Koa team has made an official fork of it under the name @koa/router
.
对于阅读本文的人,谁对如何在Koa 2.X中做到这一点感到好奇:
For anyone reading this, who is curious on how to do this in 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
routes/root.js
import Router from '@koa/router'
const router = new Router()
router.get('/', async (ctx, next) => {
ctx.body = 'Hello'
})
export default router
routes/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
一起构成中间件.为简单起见,我围绕它制作了一个包装器,以简化使用koa-router
的工作.使用它看起来像这样:
If you want to avoid the repetition with the routes()
and the allowedMethods()
, you can use koa-compose
to compose the middleware together. For simplicity, I made a wrapper around it to simplify working with koa-router
. Using it would look something like this:
app.js
import Koa from 'koa'
import router from './routes'
const app = new Koa()
app.use(router())
export default app
routes/index.js
import combineRouters from 'koa-combine-routers'
import rootRouter from './root'
import userRouter from './user'
const router = combineRouters(
rootRouter,
userRouter
)
export default router
它会做同样的事情.
这篇关于如何将Koa路由拆分为单独的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!