Node

116 阅读1分钟

Koa

别名:把一些常用的属性和方法挂在到ctx上

/**
 *  new Koa -> Application   实例
 *  context 上下文对象
        ctx -> context 上下文对象
        ctx.request 请求对象
        ctx.response 响应对象
        
        ctx.res -> res
        ctx.req -> req
 */
const Koa = require("koa");

const app = new Koa();

app.use((ctx) => {
    //   ctx.body = "你好 世界";
    //   ctx.body = {
    //       msg:"你好 世界"
    //   };
     // end()

// 别名:把一些常用的属性和方法挂在到ctx上
// 发给浏览器的 都找响应对象
// 浏览器发过来的 都找请求对象
// ctx.body = "hello world";
ctx.response.body = "hello world"
  
});
app.listen(8081);

洋葱模型

// 中间件: use里的这个函数
// 添加中间件
app.use((ctx, next) => {
  console.log(">>>> fn1");
  next();
  console.log("<<<< fn1 ------------------------");
  ctx.body = "fn1"
});

app.use((ctx, next) => {
  console.log(">>>> fn2");
  next()
  console.log("<<<< fn2");
  ctx.body = "fn2"
});

app.use((ctx, next) => {
  console.log(">>>> fn3");
  next()
  console.log("<<<< fn3");
});

从请求到响应的总时间

// log 日志
app.use((ctx, next) => {
  const startTime = Date.now();
  next();
  console.log("time:", Date.now() - startTime);
});

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

异步

app.use(async (ctx, next) => {
  const startTime = Date.now();
  await next();
  console.log("time:", Date.now() - startTime);
});

app.use(async (ctx) => {
  await delay();
  ctx.body = "hahahah ";
});

function delay() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, 2000);
  });
}

在多个中间件内传递参数

// 在多个中间件内传递参数
app.use((ctx, next) => {
  ctx.kkb = {
    name: "hahah",
  };
  next()
});

app.use((ctx) => {
  console.log(ctx.kkb.name);
});

app.listen(8081);

http 状态码

模拟302重定向

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

app.use((ctx) => {
    ctx.status = 302
    ctx.set('location', 'https://cn.bing.com/')
})

app.listen(8081)