最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Enabling gzip compression with fetch.js - Stack Overflow

programmeradmin3浏览0评论

I'm using fetch.js () to send a relatively large json object to the backend. The json is large in that it include an SVG image string.

Does fetch.js use gzip compression by default, or do I need to manually compress and add headers?

return new Promise((resolve, reject) => {
  fetch(api_base + "/api/save-photo", {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
  })
    .then((response) => {
      if (response.status === 404) {
        throw new Error('404 (Not Found)');
      } else {
        return response.json().then((json) => {
          console.log('save poster response: ', json);
          return json;
        });
      }
    });
});

I'm using fetch.js (https://github.com/github/fetch) to send a relatively large json object to the backend. The json is large in that it include an SVG image string.

Does fetch.js use gzip compression by default, or do I need to manually compress and add headers?

return new Promise((resolve, reject) => {
  fetch(api_base + "/api/save-photo", {
    method: 'POST',
    mode: 'cors',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(payload)
  })
    .then((response) => {
      if (response.status === 404) {
        throw new Error('404 (Not Found)');
      } else {
        return response.json().then((json) => {
          console.log('save poster response: ', json);
          return json;
        });
      }
    });
});
Share Improve this question edited Sep 24, 2022 at 3:56 starball 50.4k32 gold badges202 silver badges882 bronze badges asked Aug 29, 2017 at 15:53 shackletonshackleton 7931 gold badge13 silver badges32 bronze badges 2
  • 1 Whether .js or .json will be gzip compress or not usually is configured at the server level (i.e. Apache or Nginx) on its way of handling http than at the application level. – hcheung Commented Apr 27, 2018 at 7:49
  • What is the explicit promise construction antipattern and how do I avoid it? – VLAZ Commented Mar 21, 2022 at 8:29
Add a comment  | 

2 Answers 2

Reset to default 10

Use https://github.com/nodeca/pako (a faster port of zlib).

Add the following import:

import { gzip } from 'pako';

Then, change:

body: JSON.stringify(payload)

To:

body: await gzip(JSON.stringify(payload))

And add the header:

'Content-Encoding': 'gzip',

Or, if you don't use the await/async syntax, your example code becomes:

return new Promise((resolve, reject) => {
  gzip(JSON.stringify(payload)).then((gzippedBody) => {
    fetch(api_base + "/api/save-photo", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Encoding': 'gzip',
        'Content-Type': 'application/json'
      },
      body: gzippedBody
    })
      .then((response) => {
        if (response.status === 404) {
          throw new Error('404 (Not Found)');
        } else {
          return response.json().then((json) => {
            console.log('save poster response: ', json);
            return json;
          });
        }
      });
  });
});

I'm assuming that with your line of

body: JSON.stringify(payload)

that payload isn't compressed.

I also wanted to be able to zip/compress a payload body and I also need an async approach to fit with the rest of my code. The bit I was struggling with was finding a way to use zlib without callbacks.

To achieve this, I did the following....

In a separate help library, I import zib...

import zlib from 'zlib'

I created the following functions....

async function asyncCompressBody(body) {

    const compressedData = await compressBody(body);
    console.log("Data Compressed");

    return compressedData;

}

function compressBody(body) {

    return new Promise( function( resolve, reject ) {

        zlib.deflate(body, (err, buffer) => {
            if(err){
                console.log("Error Zipping");
                reject(err);
            }

            console.log("Zipped");

            resolve(buffer);
        });
    });

}

The compressBody function is a promise around zlib.deflate. The function asyncCompressBody is an async function that allows the calling function to await.

In the calling function, I use it as...

let compressedBody = await asyncCompressBody(jsonContent);

let headers = new Headers();
headers.append("Content-Type","application/json");
headers.append("Content-Encoding","zlib");

const response = await fetch(url,
    {method: 'POST',
    headers:headers,
    body:compressedBody});
发布评论

评论列表(0)

  1. 暂无评论