最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AWS Lambda: How do I get property inside event.body, it keep return undefined - Stack Overflow

programmeradmin1浏览0评论

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?

Share Improve this question asked Feb 9, 2021 at 7:19 JoelJoel 531 silver badge6 bronze badges 2
  • Can you post your event as text in code block, not screenshot? – Marcin Commented Feb 9, 2021 at 7:32
  • I kept getting None and everything else is there, this is unbelievably hard to get right – momo668 Commented Apr 3, 2023 at 11:13
Add a ment  | 

3 Answers 3

Reset to default 4

Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:

exports.handler = function(event, context, callback) {
  const body = JSON.parse(event.body)
  console.log('data: ', body.data)
}

Then apply the suggestions from @Marcin and fix your JSON data because it's missing quotes.

Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.

It should be:

'{"action": "message, "data": "black clolor"}'

not

"{action: 'message, data: 'black clolor'}"

Thanks @Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.

Changing it to the code below solved the issue.

{"action": "message", "data": "black clolor"}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论