使用fetch.js启用gzip压缩 [英] Enabling gzip compression with fetch.js
问题描述
我正在使用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屋!