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

How to get a correct response from an API on AWS lambda

这是我第一次向 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})
};

非常感谢您的帮助,

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

在此处阅读更多内容:

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

我自己 运行 最近才陷入这个问题。解决方案是:

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

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

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

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

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