Koa2系列第二篇:中间件

632 阅读1分钟

第一篇介绍了生成器目录设计

接下来学习Koa2的中间件。

Koa2本身只能算一个极简的HTTP服务器,自身不内置中间件,但是提供中间件内核。中间件是Koa2的核心,因此需要熟练掌握。

中间件是什么?

你可以把一个HTTP请求理解为水流,而各种各样的中间件类似各种管道,它会对水流进行处理。每个中间件在HTTP请求过程中会改写请求,响应等数据。

也就是我们常说的洋葱模型。

我们可以通过一个实例理解上述的过程:


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



// 日志中间件
app.use(async (ctx, next) => {
  console.log('middleware before await');
  const start = new Date()
  await next() // 函数控制权转移
  console.log('middleware after await');
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async(ctx, next) => {
  console.log('response');
  ctx.body = "hello koa2"
})

module.exports = app

终端打印

middleware before await
response
middleware after await

中间件写法

通用函数中间件

// 日志中间件
app.use((ctx, next) => {
  console.log('middleware before await');
  const start = new Date()
  return next().then(() => {
    console.log('middleware after await');
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
  })
})

上述写法不够简洁。

生成器函数中间件


const convert = require('koa-convert');

// 日志中间件
app.use(function* log(next) {
  console.log('middleware before await');
  const start = new Date()
  yield next
  const ms = new Date() - start
  console.log(`${this.method} ${this.url} - ${ms}ms`)
})

这里有个小细节,因为我们这里中间件没有使用箭头函数,因此其实这里的this就是我们平时说的上下文对象ctx。这也说明了使用async箭头函数式中间件时候,为什么Koa2需要显示提供ctx对象, 就是为了解决此处用this引用会有问题。

async函数中间件

app.use(async ctx => {
  ctx.body = 'Hello World';
});

上下文对象

在Koa2中,ctx是一次完整的HTTP请求的上下文,会贯穿这个请求的生命周期。也就是说在整个请求阶段都是共享的。


  createContext(req, res) {
    const context = Object.create(this.context);
    // request、response是Koa2内置的对象
    // 业务中我们一般通过ctx.request、ctx.response访问
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    // 挂在app自身
    context.app = request.app = response.app = this;
    // 挂在node原生的内置对象
    // req: http://nodejs.cn/api/http.html#http_class_http_incomingmessage
    // res: http://nodejs.cn/api/http.html#http_class_http_serverresponse
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    // 最初的URL
    context.originalUrl = request.originalUrl = req.url;
    // 一个中间件生命周期内公共的存储空间
    context.state = {};
    return context;
  }

ctx.body

ctx.body主要是Koa2返回数据到客户端的方法。


// context.js
/**
 * Response delegation.
 */

delegate(proto, 'response')
  .access('body')

可见ctx.body实际上是对在response.js的body进行赋值操作。

ctx.body的一些特性:

  • 可以直接返回一个文本
  • 可以返回一个HTML文本
  • 可以返回JSON

ctx.body = 'hello'

ctx.body = '<h2>h2</h2>'

ctx.body = {
  name: 'kobe'
}

get status() {
    return this.res.statusCode;
  },

  /**
   * Set response status code.
   *
   * @param {Number} code
   * @api public
   */

  set status(code) {
    if (this.headerSent) return;

    assert(Number.isInteger(code), 'status code must be a number');
    assert(code >= 100 && code <= 999, `invalid status code: ${code}`);
    this._explicitStatus = true;
    this.res.statusCode = code;
    // 客户端发送的 HTTP 版本,message.httpVersionMajor 是第一个整数, message.httpVersionMinor 是第二个整数。
    // http://nodejs.cn/api/http.html#http_message_httpversion
    // 设置状态消息 http://nodejs.cn/api/http.html#http_response_statusmessage
    if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];
    if (this.body && statuses.empty[code]) this.body = null;
  }, 

/**
   * Set response body.
   *
   * @param {String|Buffer|Object|Stream} val
   * @api public
   */

  set body(val) {
    // this._body是真正的body属性或者说代理属性
    const original = this._body;
    this._body = val;

    // no content
    if (null == val) {
      // 204 "no content"
      if (!statuses.empty[this.status]) this.status = 204;
      if (val === null) this._explicitNullBody = true;
      this.remove('Content-Type');
      this.remove('Content-Length');
      this.remove('Transfer-Encoding');
      return;
    }

    // 设置状态码
    if (!this._explicitStatus) this.status = 200;

    // 设置content-type
    const setType = !this.has('Content-Type');

    // string
    if ('string' === typeof val) {
      // text/html or text/plain
      if (setType) this.type = /^\s*</.test(val) ? 'html' : 'text';
      this.length = Buffer.byteLength(val);
      return;
    }

    // buffer
    if (Buffer.isBuffer(val)) {
      if (setType) this.type = 'bin';
      this.length = val.length;
      return;
    }

    // stream
    if (val instanceof Stream) {
      onFinish(this.res, destroy.bind(null, val));
      if (original != val) {
        val.once('error', err => this.ctx.onerror(err));
        // overwriting
        if (null != original) this.remove('Content-Length');
      }

      if (setType) this.type = 'bin';
      return;
    }

    // json
    this.remove('Content-Length');
    this.type = 'json';
  },

ctx.body的工作原理就是根据其赋值的类型,来对Content-Type头进行处理,最后根据Content-Type类型值通过res.end,把数据写入到浏览器。

ctx.redirect

浏览器重定向一般是向前或者向后重定向。


redirect(url, alt) {
    // location
    if ('back' === url) url = this.ctx.get('Referrer') || alt || '/';
    this.set('Location', encodeUrl(url));

    // status
    if (!statuses.redirect[this.status]) this.status = 302;

    // html
    if (this.ctx.accepts('html')) {
      url = escape(url);
      this.type = 'text/html; charset=utf-8';
      this.body = `Redirecting to <a href="${url}">${url}</a>.`;
      return;
    }

    // text
    this.type = 'text/plain; charset=utf-8';
    this.body = `Redirecting to ${url}.`;
  },

关于中间件源码在下一个系列文章。

ps: 不介意可以关注我的公众号 xyz_编程日记 、加好友、点👍、点在看。