AWS Lambda newbie here. I was doing some testing with AWS Lambda functions and there is something that it is not working correct for me. Given this lambda function:
exports.handler = async (event, context, callback) => {
var response = {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
response: event.talk
};
callback(null, response);
};
When I press the test button with this content (here is a screenshot):
{
"talk": "Hello World"
}
I get this response (here is a screenshot):
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"response": "Hello World"
}
But when I make a POST request (I added an open API gateway, see it here), it just returns empty data and sometimes internal server error (here is a screenshot):
no data
If I modify my Lambda function to JSON parse the body, it will work
exports.handler = async (event, context, callback) => {
var body = JSON.parse(event.body);
var talk = body.talk;
var response = {
statusCode: 200,
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(talk)
};
callback(null, response);
};
What it is happening? Why the test button work differently from a POST request? I want both to work, specially the test because I want to "debug" the "serverless"
When You call AWS lambda handle request what you pass in the request.
So, When you need to pass data in
eventwith body just addbodyparams ineventObject.
{
"body": "{\"talk\":\"Hello World\"}"
}
Note:
When you Call lambda from
POSTthen request Object containbodyin the event.
The test button will simply run your lambda with the event provided, but when you run it through API gateway proxy, you get an event in a different format. As to why it works when you parse event.body, it's because event.body will contain the message being sent through the API.
The best thing to do would be to do:
console.log(JSON.stringify(event));
And view the incoming event format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With