Koa 应用生成器以及 Koa 路由模块化

一、koa 应用生成器

通过应用 koa 脚手架生成工具 可以快速创建一个基于 koa2 的应用的骨架。

 

1、全局安装

 

npm install koa-generator -g

2、创建项目

koa koa_demo

3、安装依赖

cd koa_demo 
npm install

4、启动项目

npm start

koa 搭建模块化路由/层级路由

1、在目录下面新建一个文件夹 routes

2、在 routes 里面配置对应的子页面

3、比如在 routes 新建 index.js

const Router = require('koa-router');
let router = new Router();
router.get('/', async (ctx) => {
    ctx.body = "这是前台首页";
})
router.get('/news', async (ctx) => {
    ctx.body = '这是前台新闻页面';
})
router.get('/user', async (ctx) => {
    ctx.body = '这是用户页面';
})
module.exports = router;

 

4然后在主应用中加载子路由模块:

const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
let index = require('./module/index.js');
let admin = require('./module/admin.js');
//装载所有子路由
let router = new Router();
router.use('/index',index.routes()); 
router.use(' / ',home.routes());
    //加载路由中间件
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
    console.log('[demo] server is starting at port 3000');
});

posted on 2020-02-03 13:41  LoaderMan  阅读(442)  评论(0编辑  收藏  举报

导航