I have the app setup like below and I want to get the Lambda’s response through API to show the item list in web.
User <-> API Gateway <-> Lambda <-> DynamoDB
Below is the example of code I’m using.
// React component
async handleSubmit(event) {
event.preventDefault();
const res = await axios.post('https://***.execute-api.us-east-1.amazonaws.com/default/functionName', {})
console.log(res)
}
// It returns "null" and nothing in Payload.
// Lambda Function
client = boto3.client('dynamodb', region_name='us-east-1')
data = client.scan(TableName='myTable');
response = {
'statusCode': 200,
'body': json.dumps(data),
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
}
return response;
// Lambda Function Test response is;
{
"statusCode": 200,
"body": "{"Items": [{"date": {"N": "123"}, "message": {"S": "msg"}}....], "Count": .....",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}
In Lambda, I can get the list of DynamoDB items in JSON format without issue. Do you have any idea why I get "Null" in React? What am I missing?
2
Answers
I found the issue was from my API Gateway setup. I created an HTTP API, set Route with GET method with Lambda function integration. It works!
Just as you do in the React side, you need to properly handle the promise on
the Lambda side. Something more like: