我在文件app.js
中有很多代码,其中一些像下面
const Router = require('koa-router')
const router = new Router()
router.get('/', async ( ctx )=>{ //lots of codes})
router.get('/help', async ( ctx )=>{ //lots of codes})
router.get('/signup', async ( ctx )=>{ //lots of codes})
router.get('/signin', async ( ctx )=>{ //lots of codes})
//and more codes
现在我想从这些路由器中精简app.js
,我创建了一个名为routers
的文件夹,我为每个路由器制作每个 js 文件,例如help.js
、signup.js
、signin.js
,我该如何写入这些路由器文件? 以及如何在app.js
中使用它们?
你可以像这样处理你的文件:
索引.js ( 包含所有路由 ( 用户.js、上传.js、统计数据.js等。
让我们从用户.js文件开始 在这里,您可以拥有多种功能,例如:
exports.getOne = async (ctx) => {
// your custom code here
}
exports.getAll = async (ctx) => {
// your custom code here
}
在您的索引中.js
const Router = require('koa-router')
const router = new Router()
const users = require('./users')
router
.get('/api/path/get', users.getOne)
.get('/api/path/get', users.getAll)
然后在你的应用中.js你有:
const api = require('./api/index')
app.use(api.routes())
您的help.js
可能如下所示:
'use strict';
exports.get = async (ctx, next) => {
// your code goes here
}
exports.post = async (ctx, next) => {
// your code goes here
}
在app.js
中,您可以执行以下操作:
...
const help = require('./help'));
...
router
.get('/help', help.get);
.post('/help', help.post);