koa.js基础概念

koa

Koa中最重要的概念:middleware, context, request, response

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

// koa 中间件的写法与执行顺序
app.use(async (ctx, next) => {
    // 1
    await next(); // 2
    console.log(`${ctx.method} ${ctx.url} ${ctx.response.get('X-Res-Time')}`); // 8
});

app.use(async (ctx, next) => {
    const start = Date.now(); // 3
    await next(); //4
    const ms = Date.now() - start; // 6
    ctx.response.set('X-Res-Time', `${ms}ms`); // 7
});

app.use(async ctx => {
    ctx.body = 'hello koajs'; // 5
});

app.listen(3000); // http.createServer(app.callback()).listen(3000);

1.1 Context

Context对象在每次请求的时候创建,它主要是对nodejs的requestresponse的封装

app.use(async ctx => {
  ctx; // is the Context
  ctx.request; // is a Koa Request
  ctx.response; // is a Koa Response
  ctx.app; // is a Koa Application
  ctx.state.user = await User.find(id); 
  // ctx.state is the recommended namespace for passing information through middleware
  ctx.cookie; // cookie object
});

1.2 Request

app.use(async ctx => {
  ctx.request; // is a Koa Request
  ctx.request.header; // request header
  ctx.request.method; // request method
  ctx.request.url;    // request url
  ctx.request.query; // convert 'color=blue&size=s' to {color:'blue', size: 's'}
  ctx.request.get(field); // get specific field in header
});

1.3 Response

app.use(async ctx => {
  ctx.response; // is a Koa Request
  ctx.response.status = 200; 
  ctx.response.body = 'hello world';
  ctx.response.type = 'text/plain; charset=utf-8';
  ctx.set({
  'Etag': '1234',
  'Last-Modified': date
});
  ctx.set('Cache-Control', 'no-cache');
  const etag = ctx.response.get('ETag'); // case-insensitive
});
原文地址:https://www.cnblogs.com/elimsc/p/15046720.html