koa基础

作者: Wrestle_Mania | 来源:发表于2019-11-20 10:24 被阅读0次
    const koa = require("koa");
    const app = new koa();
    
    app.use(async ctx => {
      ctx.body = "Hello koa2";
    });
    
    app.listen(8080);
    
    const Koa = require("koa");
    const Router = require("koa-router");
    
    const app = new Koa();
    const router = new Router();
    
    router.get("/", (ctx, next) => {
      ctx.body = "Hello Koa";
    });
    
    router.get("/news", (ctx, next) => {
      ctx.body = "Hello news";
    });
    
    app.use(router.routes());
    app.use(router.allowedMethods());
    
    app.listen(8080, () => {
      console.log("starting at port 8080");
    });
    
    • 链式写法
    const Koa = require("koa");
    const Router = require("koa-router");
    
    const app = new Koa();
    const router = new Router();
    
    router
      .get("/", async (ctx, next) => {
        ctx.body = "Hello Koa";
      })
      .get("/news", async (ctx, next) => {
        ctx.body = "Hello news";
      });
    
    app.use(router.routes()).use(router.allowedMethods());
    
    app.listen(8080, () => {
      console.log("starting at port 8080");
    });
    
    • 简化写法&注释
    const Koa = require("koa");
    const router = require("koa-router")();
    
    const app = new Koa();
    
    router
      .get("/", async ctx => {
        ctx.body = "home";
      })
      .get("/news", async ctx => {
        ctx.body = "news";
      });
    
    app
      .use(router.routes()) // 启动路由
      .use(router.allowedMethods());//有一段比较操蛋的功能,先不管他
    
    app.listen(8080);
    

    相关文章

      网友评论

          本文标题:koa基础

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