Enabling gzip compression with fetch.js(使用 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 压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 fetch.js 启用 gzip 压缩


- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01