通过AWS Lambda/API网关返回JSONP [英] Return JSONP via AWS Lambda/API Gateway

查看:174
本文介绍了通过AWS Lambda/API网关返回JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以callbackname(data.strified)的形式返回jsonp

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

现在我的快速而肮脏的方式返回了数据,并且如果给出了?cb = test,它将返回:

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

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

反正还有引号和转义字符吗? 该API应该可以在不设置回调的情况下使用.

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

推荐答案

鉴于您具有这种类型的lambda函数:

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

给它一个类似的事件

{
  "cb": "callback"
}

它将给出以下输出:

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

到目前为止,太好了.现在,您进入API网关,并在集成响应"部分中编写此代码

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

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

然后,当您调用API网关端点时,将得到callback({"test":"data"})作为输出.

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

这篇关于通过AWS Lambda/API网关返回JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆