我已经创建了与AWS API Gateway集成的Lambda函数。 我已经从Integration Request配置了模板模型,以便可以从Lambda函数中的Event对象访问请求标头。
Integration Request Configuration :
从cloudWatch中,我观察到在代码执行期间console.log(event)并不总是为空:
以下代码生成了CloudWatch日志:
var moment = require('moment');
var AWS = require('aws-sdk');
var keyPairId = 'APKAIPZ5BRDMEXAMPLE';
var privateKey = '';
var signer = new AWS.CloudFront.Signer(keyPairId, privateKey);
var expireTime = moment().add(3600, 'sec').unix();
exports.handler = (event, context, callback) => {
console.log(event.headers); //logged twice from cloudWatch
console.log(event.headers); //Undefined although i can see the data from cloudwatch...
var domain = 'mydomain.com';
var resource = 'https://cdn.mydomain.com/*';
var attributes = '; domain=' + domain + '; path=/; secure; httpOnly'
var options = {policy : '{"Statement":[{"Resource":"' + resource +
'","Condition":{"DateLessThan":{"AWS:EpochTime":' + expireTime +
'}}}]}'};
signer.getSignedCookie(options, function(err, data) {
if (err) {
//do somehing
} else {
context.done(null, {
'Set-Cookie': 'CloudFront-Policy=' + data["CloudFront-Policy"] + attributes,
'SEt-Cookie': 'CloudFront-Signature=' + data["CloudFront-Signature"] + attributes,
'SeT-Cookie': 'CloudFront-Key-Pair-Id=' + data["CloudFront-Key-Pair-Id"] + attributes
});
}
});
};
如上面的代码所述,您能否解释一下为什么console.log(event)
从cloudWatch记录两次,而console.log(event['headers'])
却导致异常,因为尽管我可以从cloudwatch中看到数据,但报头未定义?
非常感谢!
编辑:
使用REST(CORS)调用lambda函数。我已经从浏览器记录了两个HTTP请求:
具有方法的HTTP请求:OPTIONS
OPTIONS https://mycdn-domain.net/authenticate
Access-Control-Request-Method: GET
Origin: https://origin-domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
Access-Control-Request-Headers: x-api-key
Accept: */*
带有方法GET的HTTP请求
GET https://mycdn-domain.net/authenticate
Origin: https://origin-domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
x-api-key: ************************************
Accept: */*