MikiBelavista
MikiBelavista

Reputation: 2758

How to create event response with Node 12 for AWS Lambda function?

The tutorial I am looking at is using, Node 6.1 for AWS Lambda function

export.fn = (event,context,callback) {
    callback(null,event)
};

I want to use Node.12.

exports.handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from G!'),
  };
  return response;
}

How to rewrite my function that it can accept JSON data?

{
  "persondata": {
    "name": "Max",
    "length": 29
  }
}

Response Body

{
  "statusCode": 200,
  "body": "\"Hello from G!\""
}

Logs

Mon Dec 16 11:38:57 UTC 2019 : HTTP Method: POST, Resource Path: /compare-yourself
Mon Dec 16 11:38:57 UTC 2019 : Method request path: {}
Mon Dec 16 11:38:57 UTC 2019 : Method request query string: {}
Mon Dec 16 11:38:57 UTC 2019 : Method request headers: {}
Mon Dec 16 11:38:57 UTC 2019 : Method request body before transformations: {
   "persondata" : {
     "name" : "Max", 
     "length" : 29
   }
}

Upvotes: 1

Views: 873

Answers (1)

Arun Kamalanathan
Arun Kamalanathan

Reputation: 8603

You can return a json from lambda as below:

exports.handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      "persondata": {
        "name": "Max",
        "length": 29
      }
    })
  };
  return response;
}

Upvotes: 1

Related Questions