我正在尝试从节点js lambda项目中的SNS事件中的Message获取内容
这是处理消息的代码
exports.handler = (event, context, callback) => {
var message = event.Records[0].Sns.Message;
console.log('Message received from SNS:', message);
message.Events.forEach(element => {
console.log(element);
});
};
示例事件:
{
"Records":
[
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "",
"Sns":
{
"Type": "Notification",
"MessageId": "bc86f105-c320",
"TopicArn": "arn:aws:sns:ewerwrewrw",
"Subject": "dwqweq23234",
"Message":
{
"Events":
[
{"EventTimestamp":"2018-03-16T10:51:22Z"},
{"EventTimestamp":"2018-03-16T10:51:22Z"}
],
"EventDocVersion":"2014-08-15"
},
"Timestamp": "2018-03-16T10:51:22.691Z",
"SignatureVersion": "1",
"Signature": "",
"SigningCertUrl": "",
"UnsubscribeUrl": "",
"MessageAttributes": {}
}
}
]
}
这是我在CloudWatch日志中获得的:
从SNS收到的消息: { "活动&#34 ;: [ {" EventTimestamp":" 2018-03-16T10:51:22Z"}, {" EventTimestamp":" 2018-03-16T10:51:22Z"} ] " EventDocVersion":" 2014年8月15日" }
TypeError:无法读取属性' forEach'未定义的 在exports.handler
为什么我无法解析事件'在事件中的消息对象内部?
答案 0 :(得分:2)
在我修好之后工作:
var message = event.Records[0].Sns.Message;
var msgJson = JSON.parse(message);
msgJson["Events"].forEach(element => { .....
答案 1 :(得分:0)
尝试消息[“事件”]。forEach 而不是message.Events可能会起作用并检查天气属性是否存在使用。实际上 message.Events 如果你得到这个应该可行您提到的控制台中的同一个对象,但至少可以通过检查属性来避免错误。 ----编辑---- if(message&& message.hasOwnProperty('Events'))
if(message && message.hasOwnProperty('Events')){
message.Events.forEach(element => {
console.log(element);
});
}
我认为您收到的消息是空白的,首先尝试打印,因为我在浏览器中尝试过以下工作正常:
var obj={
"Records":
[
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "",
"Sns":
{
"Type": "Notification",
"MessageId": "bc86f105-c320",
"TopicArn": "arn:aws:sns:ewerwrewrw",
"Subject": "dwqweq23234",
"Message":
{
"Events":
[
{"EventTimestamp":"2018-03-16T10:51:22Z"},
{"EventTimestamp":"2018-03-16T10:51:22Z"}
],
"EventDocVersion":"2014-08-15"
},
"Timestamp": "2018-03-16T10:51:22.691Z",
"SignatureVersion": "1",
"Signature": "",
"SigningCertUrl": "",
"UnsubscribeUrl": "",
"MessageAttributes": {}
}
}
]
};
var fun1 = function(event, context, callback){
var message = event.Records[0].Sns.Message;
console.log('Message received from SNS:', message);
console.log("starting")
message["Events"].forEach(element => {
console.log(element);
});
};
fun1(obj,'',function(){console.log("uu")})