首页 > 解决方案 > How to get a correct response from an API on AWS lambda

问题描述

This is my first time soliciting the Stack-Overflow community. Since a few days I have been learning to use the AWS lambda service connected with GETEWAY. I need to do a GET on an API but the problem is that I constantly receive a empty response.

Here is an example of my code with a free access API:


var getApi= async function(event) {
        var x =  await axios.get(url)       
}


var getResponse = async function(){
  var data= await getApi()
  if (data.status ==200){
       return data
  }

}



exports.handler = async function() {


    return getResponse().then(res => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(res), 
        };
        return response

    }).catch(error => { return error})
};

Thank you very much for your help,

标签: javascriptnode.jsapiaws-lambdaaws-serverless

解决方案


我自己最近遇到了这个问题。解决方案是:

  1. 如果您在 AWS 网关中使用 Lambda 作为授权方,则 Lambda 应返回包含 principalId、policyDocument 和 context 的 JSON 对象。
  2. 上下文是一个地图,您可以在其中添加自己的自定义变量,例如字符串、数字和布尔值。

JSON 对象的全部内容将返回到网关。查看此文档:https ://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html

我还有一篇关于如何通过 Cloudformation YAML 文件配置网关的非常详细的 Stackoverflow 帖子:AWS API Gateway with Lambda Authorizer


推荐阅读