美文网首页
路由模块化

路由模块化

作者: Wrestle_Mania | 来源:发表于2019-11-30 23:07 被阅读0次
    • app.js
    const Koa = require("koa"),
      views = require("koa-views"),
      path = require("path"),
      render = require("koa-art-template"),
      router = require("koa-router")();
    
    const admin = require("./router/admin"),
      home = require("./router/home");
    
    const app = new Koa();
    
    render(app, {
      root: path.join(__dirname, "views"),
      extname: ".html",
      debug: true
    });
    
    router.use(home);
    router.use("/admin", admin);
    
    app.use(router.routes()).use(router.allowedMethods());
    
    app.listen(8080);
    
    • router/home/index.js
    const router = require("koa-router")();
    
    router.get("/", async ctx => {
      ctx.body = "home";
    });
    
    router.get("/news", async ctx => {
      ctx.body = "news";
    });
    
    module.exports = router.routes();
    
    • router/admin/index.js
    const router = require("koa-router")();
    
    router.get("/", async ctx => {
      ctx.body = "admin";
    });
    
    router.get("/user", async ctx => {
      ctx.body = "user";
    });
    
    router.get("/list", async ctx => {
      ctx.body = "list";
    });
    
    module.exports = router.routes();
    
    

    模块细分

    • router/admin/index.js
    const router = require("koa-router")();
    
    const list = require("./list"),
      user = require("./user");
    
    router.get("/", async ctx => {
      ctx.body = "admin";
    });
    
    router.use("/list", list);
    router.use("/user", user);
    
    module.exports = router.routes();
    
    • router/admin/list.js
    const router = require("koa-router")();
    
    router.get("/", async ctx => {
      ctx.body = "list";
    });
    
    router.get("/add", async ctx => {
      ctx.body = "list-add";
    });
    
    router.get("/update", async ctx => {
      ctx.body = "list-update";
    });
    
    module.exports = router.routes();
    
    • router/admin/user.js
    const router = require("koa-router")();
    
    router.get("/", async ctx => {
      ctx.body = "user";
    });
    
    router.get("/add", async ctx => {
      ctx.body = "user-add";
    });
    
    router.get("/update", async ctx => {
      ctx.body = "user-update";
    });
    
    module.exports = router.routes();
    

    • 配合art-template
    const router = require("koa-router")();
    
    router.get("/", async ctx => {
      await ctx.render("admin/user/index");
    });
    
    router.get("/add", async ctx => {
      await ctx.render("admin/user/add");
    });
    
    router.get("/update", async ctx => {
      await ctx.render("admin/user/update");
    });
    
    module.exports = router.routes();
    

    相关文章

      网友评论

          本文标题:路由模块化

          本文链接:https://www.haomeiwen.com/subject/mrvawctx.html