egg 開啟 gzip 壓縮(tl)


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 的響應體不壓縮
};

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM