如何从 {} 对象读取属性。 NodeJS
所以我有这个后端 NodeJS Lambda,我从 Angular 向它发送数据。
我从 NodeJS Lambda 运行此代码:
const claims = event.requestContext.authorizer.claims;
username = claims['cognito:username'];
console.log(username);
console.log(event.body);
console.log(event.body['Description'])
console.log(event.body.Description)
我可以从经过身份验证的用户读取用户名,并且 event.body 打印此内容(来自 Cloudwatch 日志):
2022-03-07T19:23:11.844Z a456711f-3fc1-4aee-9864-246f51c7fe93 INFO
{
"Description": "Afspraak met dr maken",
"Day": "April 5th at 2:30pm",
"Priority": "High",
"ID": 2,
"Reminder": true
}
但这两个语句都打印未定义:
console.log(event.body['Description'])
console.log(event.body.Description)
我很确定我正在做或忘记一些非常愚蠢的事情,但似乎无法弄清楚。有人愿意帮忙吗?
So I have this backend NodeJS Lambda, I send data to it from Angular.
From the NodeJS Lambda I run this code:
const claims = event.requestContext.authorizer.claims;
username = claims['cognito:username'];
console.log(username);
console.log(event.body);
console.log(event.body['Description'])
console.log(event.body.Description)
I can read the username from the authenticated user, and the event.body prints this (from Cloudwatch logs) :
2022-03-07T19:23:11.844Z a456711f-3fc1-4aee-9864-246f51c7fe93 INFO
{
"Description": "Afspraak met dr maken",
"Day": "April 5th at 2:30pm",
"Priority": "High",
"ID": 2,
"Reminder": true
}
Both these statements print undefined though:
console.log(event.body['Description'])
console.log(event.body.Description)
I'm pretty sure i'm doing or forgetting something really stupid but can't seem to figure it out. Anybody willing to help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发现错误了!通过这样做弄清楚:
console.log(typeof event.body);
那个 event.body 只是一个字符串。
使用
body = JSON.parse(event['body'])
将其解析为 json 对象,现在我可以调用 body.Description。解决了!
Found the mistake! Figured out by doing:
console.log(typeof event.body);
That event.body was just a string.
Used
body = JSON.parse(event['body'])
to parse it into a json object and now i can call body.Description.Solved!