首页 > 其他 > 详细

egg 开启 gzip 压缩(tl)

时间:2020-07-10 13:06:09      阅读:158      评论:0      收藏:0      [点我收藏+]

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 的响应体不压缩
};

.

egg 开启 gzip 压缩(tl)

原文:https://www.cnblogs.com/crazycode2/p/13277929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!