Reputation: 1389
I am using Node.js 8.10 in lambda proxy integration. My goal is very simple.
but I faced issue in step 1. I tried to figure out and I asked aws support center. it was not helpful. please help me.
my test json data are :
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
my code is very simple but have a problem :
exports.handler = async (event) => {
var body = JSON.parse(event)//<--this is a problem
let responseBody = {
message: "hello",
key1: body.key1
};
const response = {
statusCode: 200,
headers : {"Access-Control-Allow-Origin" : "*"},
body: JSON.stringify(responseBody)
};
return response;
};
I got this error in second line.
{"errorMessage":"Unexpected token o in JSON at position 1","errorType":"SyntaxError","stackTrace":["JSON.parse (<anonymous>)","exports.handler (/var/task/index.js:2:21)"]}
So I changed second line code like this.
var body = JSON.parse(JSON.stringify(event))
and then I got response well. I thought that's working well.
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": "{\"message\":\"hello\",\"key1\":\"value1\"}"
}
but I sent same json data with postman for real. but I got only this.
{ "message": "hello" }
there isn't "key1". so I added console.log and then I checked log in cloudwatch.
{ message: 'hello', key1: undefined }
I can see aws editor log is well but when I send data with postman. lambda couldn't parse my json data. it means lambda couldn't parse event parameter.
my questions are : 1. when I tried to parse like this
var body = JSON.parse(event)"
why does lambda editor issue error? Is there something wrong? this is super simple and very common code.
How can I parse my json data and return correct value not undefined. I expected this response
{ message: 'hello', key1: 'value1' }
I have been trying to solve this for 3days. but I really have no idea. please help me out.
Upvotes: 4
Views: 15594
Reputation: 332
you need to pass the parameters in postman as JSON.
in the body tab choose the 'raw' option and then from the combo box select 'JSON' type: then just type :
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
and in your lambda function access to it like this:
JSON.parse(event.body).key1
Upvotes: 1
Reputation: 7235
The body coming from API Gateway is a stringified JSON, so you need to parse it and then access the attribute you want.
'use strict';
exports.handler = async (event) => {
let responseBody = {
message: "hello",
key1: JSON.parse(event.body).key1
};
const response = {
statusCode: 200,
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(responseBody)
};
return response;
};
This will do it.
Upvotes: 4