使用 fetch.js 启用 gzip 压缩 [英] Enabling gzip compression with fetch.js

查看:33
本文介绍了使用 fetch.js 启用 gzip 压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 fetch.js (https://github.com/github/fetch) 向后端发送一个比较大的 json 对象.json 很大,因为它包含一个 SVG 图像字符串.

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.

我不清楚 fetch.js 是否默认使用 gzip 压缩,或者我是否需要手动压缩和添加标头.任何帮助将不胜感激.

I'm not clear if fetch.js is using gzip compression by default, or if I need to manually compress and add headers. Any help would be appreciated.

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;
        });
      }
    });
});

推荐答案

我假设你的行

body: JSON.stringify(payload)

该有效负载未压缩.

我还希望能够压缩/压缩有效负载主体,并且我还需要一种异步方法来适应我的其余代码.我一直在努力解决的问题是找到一种无需回调即可使用 zlib 的方法.

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....

在单独的帮助库中,我导入 zib...

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);
        });
    });

}

compressBody 函数是围绕 zlib.deflate 的一个承诺.函数 asyncCompressBody 是一个异步函数,允许调用函数等待.

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});

这篇关于使用 fetch.js 启用 gzip 压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆