I'm new to aws and I have a strange problem of getting the body of event inside my lamda handler function.
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event.body
};
return response;
};
When I run test I get
Response:
{
"statusCode": 200
}
However when I only return event
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event <=====
};
return response;
};
I get
Response:
{
"statusCode": 200,
"body": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}
I'm using node 8.10. Does anybody knows what I'm doing wrong here?
The test event in to Lambda console is exactly what you get as the event
parameter in your Lambda handler. When you put {"a":1}
, you get {"a":1}
.
You can simulate a different event types of AWS service (SNS, S3, API Gateway) selecting a template from the combobox.
As you are returning a HTTP response, you want probably to simulate an API Gateway event, it could look like this:
{
"body": "{\"a\":1}",
"pathParameters": {
"id": "XXX"
},
"resource": "/myres",
"path": "/myres",
"httpMethod": "GET",
"isBase64Encoded": true,
"requestContext": {
"authorizer": {
"tenantId": "TEST"
},
"accountId": "123456789012",
"resourceId": "123456",
"stage": "test",
"requestId": "test-request-id",
"requestTime": "09/Apr/2015:12:34:56 +0000",
"requestTimeEpoch": 1428582896000,
"path": "/myres",
"resourcePath": "/myres,
"httpMethod": "GET",
"apiId": "1234567890",
"protocol": "HTTP/1.1"
}
}
Then you will get the body in event.body
as JSON string - you can convert it into an object by JSON.parse(event.body)
.
When returning, you have to serialize the response body with JSON.stringify
:
return {
statusCode: 200,
body: JSON.stingify({your:'object'})
};
Change
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: event.body
};
return response;
};
to
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify(event.body)
};
return response;
};
The body you return in API Gateway must be stringified, otherwise it doesn't know how to deal with the response.
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.