如果我使用gzip压缩响应,我在Google函数中的JSON响应可能会减少到70-80%。
如何从函数(通过http(S)触发)发送压缩的json响应?
这也意味着我将节省谷歌云平台的大量网络费用,并为移动用户更快地加载数据。
我试过使用zlib本机模块,但没有成功.
if (req.get('Accept-Encoding') && req.get('Accept-Encoding').indexOf('gzip') > -1) {
interpretation.gzip = true;
const zlib = require('zlib');
res.set('Content-Type', 'text/plain');
res.set('Content-Encoding', 'gzip');
zlib.gzip(JSON.stringify(interpretation), function (error, result) {
if (error) throw error;
res.status(200).send(result);
})
} else {
interpretation.gzip = false;
res.status(200).send(interpretation);
}在Postman中,响应的大小是相同的,内容类型已经改变,但是在响应中没有设置Content-Encoding头.

发布于 2018-01-24 12:09:48
看看App引擎常见问题,特别是对“如何为压缩内容提供服务?”问题的答案:
Accept-Encoding强制压缩内容,客户端可以提供“gzip”作为....To和用户-代理请求头的值。如果没有Accept-Encoding头,内容将不会被压缩.
此外,在这组职位中,有一个使用Accept-Encoding、User-Agent组合使用云函数发送请求的示例:
curl -v "https://us-central1-<project>.cloudfunctions.net/test" -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" -H "Accept-Encoding: gzip"发布于 2018-01-17 21:53:34
您可能会尝试使用zlib模块来处理压缩,并为响应设置适当的编码:
exports.helloWorld = function helloWorld(req, res) {
const zlib = require('zlib');
// Obtain JSON stream from your source...
res.status(200);
res.set('Content-Type', 'text/plain');
res.set('Content-Encoding', 'gzip');
json.pipe(zlib.createGzip()).pipe(res);
};当然,首先需要检查客户端是否接受gzip。而且,使用zlib编码可能很昂贵,结果应该被缓存。
https://stackoverflow.com/questions/48309760
复制相似问题