koa2

72 阅读1分钟

基本使用

koa-parseBody

  • 基本使用
const koa = require("koa");
const app = new koa();
const bodyParse = require('koa-bodyparser')
app.use(bodyParse())
app.use(async (ctx) => {
  if (ctx.url === "/" && ctx.method === "GET") {
    let html = `
      <h1>Hello</h1>
      <form action="/" method="POST">
            <p>name:</p>
            <input type="text" name="name">
            <p>age:</p>
            <input type="text" name="age">
            <p>submit</p>
            <button type="submit">submit</button>
      </form>
            `;
      ctx.body = html
  }else if(ctx.url==='/'&& ctx.method === 'POST'){
      ctx.body = ctx.request.body;
  }else{
      ctx.body = '<h1>404!!!</h1>'
  }
});
app.listen("5000", () => {
  console.log("net start success");
});

koa-router

  • 路由配置
const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();

const router = new Router();
router
  .get("/", (ctx, next) => {
    console.log(ctx.url);
    ctx.body = "<h1>INDEX</h1>";
  })
  .get("/todo", (ctx) => {
    ctx.body = "<h1>TODO</h1>";
  });

app.use(router.routes()).use(router.allowedMethods());

app.listen(5000, () => {
  console.log("net start success");
});

  • 多级路由配置
const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();

//子级路由
const home = new Router();
home
  .get("/", (ctx) => {
    ctx.body = "HOME1";
  })
  .get("/home2", (ctx) => {
    ctx.body = "HOME2";
  });

const page = new Router();
page
  .get("/", (ctx) => {
    ctx.body = "PAGE1";
  })
  .get("/page2", (ctx) => {
    ctx.body = "PAGE2";
  });

//父级路由
const router = new Router();

//给父级路由装载子路由
router.use('/home',home.routes(),home.allowedMethods())
router.use('/page',page.routes(),page.allowedMethods())

app.use(router.routes()).use(router.allowedMethods());

app.listen(5000, () => {
  console.log("net start success");
});

Cookie

const Koa = require("koa");
const app = new Koa();

app.use(async (ctx) => {
  if (ctx.url === "/index") {
    ctx.cookies.set("name", "xiaoming", {
      domain: "127.0.0.1",
      path: "/index",
      maxAge: 1000 * 60 * 60,
      expires: new Date("2022-11-1"),
      httpOnly: false, //不只允许http访问
      overwrite: false, //不允许重写
    });
    ctx.body = 'Cookie is ok'
  } else {
    if (ctx.cookies.get('name')) ctx.body = ctx.cookies.get("name");
    else ctx.body = 'Cookie is NULL'
  }
});

app.listen(5000, () => {
  console.log("net serve start");
});

ejs和koa-views

/views/demo.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%=title%></title>
  </head>
  <body>
    <%= title %>
  </body>
</html>

ejs.js

const Koa = require('koa')
const views = require('koa-views')
const app = new Koa()

app.use(views(__dirname+'/views',{
      extension: 'ejs'
}))

app.use(async (ctx)=>{
      let title = 'ejs'
      await ctx.render('demo',{title})
})

app.listen(5000,()=>{
      console.log('new server scucces');
})

访问静态资源 koa-static

使用http://127.0.0.1:5000/文件名进行访问

const koa = require("koa");
const static = require("koa-static");
const app = new koa();

app.use(static(__dirname + "/static"), {
  index: false, // 默认为true  访问的文件为index.html  可以修改为别的文件名或者false
  hidden: false, // 是否同意传输隐藏文件
  defer: true, // 如果为true,则在返回next()之后进行服务,从而允许后续中间件先进行响应
});

app.use(async (ctx) => {
  ctx.body = "INDEX";
});

app.listen(5000, () => {
  console.log("net start sucess");
});