Avinash
Avinash

Reputation: 147

Serverless offline response issue while sending JSON response in lambda function

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

Upvotes: 5

Views: 7063

Answers (1)

Quentin Hayot
Quentin Hayot

Reputation: 7876

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);

Upvotes: 8

Related Questions