我正在尝试使用nodeJS本地读取一个JS文件(压缩,以便它可以适应lambda边缘限制)并在响应中返回它,但我从标题中得到错误。这是为什么? aws Edge 是否禁止 gzip 正文?
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
var noCacheHeaders = {
'cache-control': [{
key: 'Cache-Control',
value: 'no-cache'
}],
'pragma': [{
key: 'Pragma',
value: 'no-cache'
}],
'content-type': [{
key: 'Content-Type',
value: 'text/html'
}]
};
if (request.uri.startsWith('/js/') === true) {
console.log("js path");
const fs = require('fs');
fs.readFile('js.gz', function(err, data) {
if (err) {
console.log(err);
// prevent caching on errors
const response = {
status: '500',
statusDescription: 'OK',
headers: noCacheHeaders,
body: "",
};
callback(null, response);
} else {
const response = {
status: '200',
statusDescription: 'OK',
headers: noCacheHeaders,//cachedHeaders,
body: data.toString(),
};
callback(null, response);
}
});
return;
}
callback(null, request);
return;
};
最佳答案
Gzip 压缩的内容不是字符数据——它是二进制数据——这意味着它不能直接序列化为 JSON。由于 response
对象通过 callback()
自动序列化为 JSON,因此数据需要进行 Base64 编码(因为任何任意二进制数据的 Base64 总是会产生干净的字符数据) ),然后 CloudFront 需要知道您做了什么,以便它可以将其解码回二进制并将其交给浏览器。
原则上,您需要类似这样的东西:
const response = {
status: '200',
statusDescription: 'OK',
headers: noCacheHeaders, //cachedHeaders,
body: data.toString('base64'), // assuming data is a buffer here (?), encode it
bodyEncoding: 'base64', // tell CloudFront it's base64; CloudFront will decode back to binary
};
关于node.js - lambda 边缘 "The Lambda function returned invalid json: The json output is not parsable.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198789/