简体   繁体   中英

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

在此处输入图像描述

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM