我尝试使用nodeJS在本地读取一个JS文件(压缩后的文件,这样它就可以满足λ边缘限制),并在响应中返回它,但我从title中得到了错误。为什么会这样呢?aws edge是否禁止gzip body?
'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;
};
发布于 2018-01-11 19:47:00
压缩后的内容不是字符数据,而是二进制数据,这意味着它不能直接序列化为JSON。由于callback()
自动将response
对象序列化为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
};
https://stackoverflow.com/questions/48198789
复制相似问题