5
var result = [{
                count : 10,
                data : [{"id":11,"id":22}]
               }];
var response = {
                statusCode: 200,
                count: result.length,
                body: result
            };
            callback(null, response);

Error on Console

According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object

Avinash
  • 137
  • 1
  • 10

1 Answers1

8

The error here gives you the solution.
API Gateway's callback expects a string and not a javascript object. You have to stringify it before passing it to the callback:

var result = [{
                count : 10,
                data : [{"id":11,"id":22}]
               }];
var response = {
                statusCode: 200,
                count: result.length,
                body: result
            };
            callback(null, JSON.stringify(response));

EDIT:
Then on the client side parse the JSON string to get it back to an object (this example assume that your client is Javascript too):

var myObject = JSON.parse(responseBody);
Quentin Hayot
  • 7,786
  • 6
  • 45
  • 62
  • yes...but i want only ***JSON*** object on client side as response – Avinash Sep 21 '18 at 12:11
  • Your client should parse the JSON string returned by your service. See my edit. – Quentin Hayot Sep 21 '18 at 13:27
  • Is any alternative way to send JSON object from lambda function...?? – Avinash Sep 24 '18 at 08:14
  • This is a JSON object. You are trying to send a JavaScript object. My code transforms it in JSON for transport and then back to a JavaScript object at destination. You can’t send a JavaScript object directly. – Quentin Hayot Sep 24 '18 at 13:03
  • Same code of mine is working on server and also get proper response.....but it fails while I m cloning from git lab and run it on locally.....its shows **According to the API Gateway specs, the body content must be stringified. Check your Lambda response and make sure you are invoking JSON.stringify(YOUR_CONTENT) on your body object** – Avinash Sep 25 '18 at 07:50
  • My solutions does exactly what the specs tells you to do. It’s possible the API Gateway now does JSON.stringify for you if you pass a JavaScript object. Serverless does not locally, so just listen to the warning and stringify your output. – Quentin Hayot Sep 25 '18 at 07:58
  • hi Quentin Hayout....fixed above issue using **serverless-offline": "3.25.6"** version – Avinash Sep 26 '18 at 10:01