问题
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.
回答1:
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.
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/37436728/return-jsonp-via-aws-lambda-api-gateway