如何从AWS Lambda上的API获得正确的响应

时间:2019-10-31 17:48:45

标签: javascript node.js api aws-lambda aws-serverless

这是我第一次征集Stack-Overflow社区。 几天以来,我一直在学习使用与GETEWAY连接的AWS lambda服务。 我需要在API上执行GET,但问题是我不断收到空响应。

这是我的带有免费访问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})
};

非常感谢您的帮助,

3 个答案:

答案 0 :(得分:0)

我建议在整个文件中使用console.log()进行调试。默认情况下,您应该能够在Cloudwatch中看到对这些控制台日志的响应:)

在此处了解更多信息

https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-logs.html

答案 1 :(得分:0)

我本人最近就遇到了这个问题。解决方案是:

  1. 如果您将Lambda用作AWS Gateway中的授权者,则Lambda应该返回一个包含PrincipalId,policyDocument和上下文的JSON对象。
  2. 上下文是一个映射,您可以在其中添加自己的自定义变量,例如字符串,数字和布尔值。

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

我也有一个非常详细的Stackoverflow帖子,介绍如何通过Cloudformation YAML文件配置网关:AWS API Gateway with Lambda Authorizer

答案 2 :(得分:0)

这是因为node.js异步调用。  您的函数在异步调用返回之前完成运行。  我修复了一些代码行。希望对您有帮助。

const getApi= async function() {
   return await axios.get(url)
}

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

exports.handler = async function() {
    return await getResponse().then(res => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(res), 
        }
        return response
    }).catch(error => console.error(error))
}