如何在nodejs和koa2中瘦身应用程序.js



我在文件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.jssignup.jssignin.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);

最新更新