1.安装 zlib

yarn add zlib

2.创建中间件

app/middleware/gzip.js

const isJSON = require("koa-is-json");
const zlib = require("zlib");

module.exports = (options) => {
  return async function gzip(ctx, next) {
    await next();

    // 后续中间件执行完成后将响应体转换成 gzip
    let body = ctx.body;
    if (!body) return;

    // 支持 options.threshold
    if (options.threshold && ctx.length < options.threshold) return;

    if (isJSON(body)) body = JSON.stringify(body);

    // 设置 gzip body,修正响应头
    const stream = zlib.createGzip();
    stream.end(body);
    ctx.body = stream;
    ctx.set("Content-Encoding", "gzip");
  };
};

3.配置

config/config.default.js

// add your middleware config here
config.middleware = ["gzip"];

config.gzip = {
  threshold: 1024, // 小于 1k 的响应体不压缩
};

.

相关文章:

  • 2021-10-01
  • 2022-02-05
  • 2022-12-23
  • 2021-12-23
  • 2021-09-04
  • 2022-12-23
猜你喜欢
  • 2021-07-18
  • 2021-12-12
  • 2021-10-22
  • 2021-09-02
  • 2022-01-18
  • 2021-12-28
  • 2022-02-01
相关资源
相似解决方案