Node.js Lambda edge“;Lambda函数返回的json无效:json输出不可解析;
我试图使用nodeJS在本地读取一个JS文件(gzip,以便它能够满足lambda边缘限制),并在响应中返回它,但我从title中得到了错误。为什么呢?aws edge是否禁止gzip主体Node.js Lambda edge“;Lambda函数返回的json无效:json输出不可解析;,node.js,amazon-web-services,aws-lambda,Node.js,Amazon Web Services,Aws Lambda,我试图使用nodeJS在本地读取一个JS文件(gzip,以便它能够满足lambda边缘限制),并在响应中返回它,但我从title中得到了错误。为什么呢?aws edge是否禁止gzip主体 'use strict'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; var noCacheHeaders = { '
'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
};
看起来您是以text/html内容类型发送响应,而不是JSON,否?@xdumaine JSON指的是当CloudFront调用此函数时传递给
callback()
并从Lambda接收的响应
或请求
对象的序列化。它在幕后总是一个JSON API,CloudFront不喜欢该文档的格式。对于gzip(在CloudFront中)webp映像,“内容类型”应该是“image/webp”吗?当我在cloudfront中启用gzip时,它会因而中断。Lambda函数返回了无效的json输出,解析的json应该是对象类型。
,除了将其更改为非缓存之外,我已经拥有了您在此处编写的内容。。也没有“statusDescription”,但看不出它有多重要。似乎您不应该使用gzip images=>