你的浏览器不支持canvas

Enjoy life!

koa

Date: Author: JM

本文章采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。

其他链接:

一、第一个koa的应用 - hello world

  • 代码
// index.js
const koa = require('koa');
const app = new koa();

app.use(async (ctx, next) => {
  await next();
  ctx.response.type = 'text/html';
  ctx.response.body = '<h1>hello world</h1>';
});

app.listen(3001);

二、ctx

const koa = require('koa');
const app = new koa();

app.use(async (ctx, next) => {
  await next();
  ctx.response.type = 'json';
  ctx.response.body = JSON.stringify({
    ctx: ctx
  });
});

app.listen(3001);
  • 结果图:

ctx

  • 由上图可以看出,ctx 是一个对象,其包含 response(即:http.ServerResponse 对象)和 request (即:http.IncomingMessage 对象)。

三、ctx.response 和 ctx.request

const koa = require('koa');
const app = new koa();

app.use(async (ctx, next) => {
  await next();
  ctx.response.type = 'json';
  ctx.response.body = JSON.stringify({
    res: ctx.response,
    req: ctx.request
  });
});

app.listen(3001);
  • 结果图:

ctx


对于本文内容有问题或建议的小伙伴,欢迎在文章底部留言交流讨论。