JSONP return via AWS Lambda / API Gateway

I am trying to return jsonp as in callbackname (data.strified)

callback( null, 
    ( !!event.cb && event.cb.length > 0 ) 
    ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
    : data
);

My quick and dirty way is now returning data, and if? cb = test, it returns:

"test({\"valid\":false,\"data\":false})"

Is there a way to get rid of quotes and escape characters? The API should work with and without a set of callbacks.

+2
source share
3 answers

Given that you have this type of lambda function:

exports.handler = function(event, context) {
    var data={"test":"data"};
    context.done( null, 
            ( !!event.cb && event.cb.length > 0 ) 
            ? event.cb.replace( /[^a-z0-9_]/i, '' ) + '(' + JSON.stringify( data ) + ')'
            : data
    );
};

When you give it an event like

{
  "cb": "callback"
}

He will give this result:

"callback({\"test\":\"data\"})"

So far so good. Now you go to the Gateway API and in the Integration Response section you write this

$util.parseJson($input.json('$'))

What will you get callback({"test":"data"})as output when you call the API gateway endpoint.

+3

. - .

$util.parseJson($input.json('$'))

.

+1

As Chagatai Gyurturk noted, you tighten your result and return it.

However, if your lambda also accepts non-callbacks, you can check the VTL pattern:

API gateway and part of the integration response:

#if($input.params('callback') != "")
$util.parseJson($input.json('$'))
#else
$input.json('$')
#end
+1
source

Source: https://habr.com/ru/post/1656638/


All Articles