zoukankan      html  css  js  c++  java
  • 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');
    });
  • 相关阅读:
    【洛谷P2860】冗余路径
    【CF1042D】Petya and Array 离散化+树状数组
    【洛谷P2127】序列排序
    【洛谷P4462】异或序列
    【SPOJ10707】COT2
    【CF1119D】Frets On Fire
    【CF1119E】Pavel and Triangles
    【洛谷P1903】数颜色
    hdu 3488(KM算法||最小费用最大流)
    hdu 1853(拆点判环+费用流)
  • 原文地址:https://www.cnblogs.com/loaderman/p/11512060.html
Copyright © 2011-2022 走看看