如何从 {} 对象读取属性。 NodeJS

发布于 2025-01-12 05:58:49 字数 838 浏览 2 评论 0原文

所以我有这个后端 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海拔太高太耀眼 2025-01-19 05:58:49

发现错误了!通过这样做弄清楚:
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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文