Joel
Joel

Reputation: 53

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

enter image description here

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?

Upvotes: 2

Views: 8815

Answers (3)

Joel
Joel

Reputation: 53

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"}

Upvotes: 1

Marcin
Marcin

Reputation: 238249

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'}"

Upvotes: 1

s.hesse
s.hesse

Reputation: 2060

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.

Upvotes: 4

Related Questions