简体   繁体   中英

Return JSONP via AWS Lambda/API Gateway

I'm 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 now returns the data and if ?cb=test is given it returns:

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

Is there anyway to get rid of the quotes and escape characters? The API should work with and without callback set.

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"
}

It will give this output:

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

So far, so good. Now you come to API Gateway and in Integration Response part you write this

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

Than you will get callback({"test":"data"}) as output when you invoke the API Gateway endpoint.

You can use an integration mapping template to do this. Something like this should help you to parse the Json.

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

Here are more details about mapping templates.

As Çağatay Gürtürk pointed out, you stringify your result and return it.

However, if your lambda also accepts non callbacks, you can check in the VTL template:

API Gateway and in Integration Response part:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM