[英]How to get a correct response from an API on AWS lambda
This is my first time soliciting the Stack-Overflow community.这是我第一次向 Stack-Overflow 社区征求意见。 Since a few days I have been learning to use the AWS lambda service connected with GETEWAY.
几天以来,我一直在学习使用与 GETEWAY 连接的 AWS lambda 服务。 I need to do a GET on an API but the problem is that I constantly receive a empty response.
我需要在 API 上执行 GET,但问题是我经常收到一个空响应。
Here is an example of my code with a free access API:这是我的代码示例,可免费访问 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,非常感谢您的帮助,
I would suggest using console.log()
all over the file to debug.我建议在整个文件中使用
console.log()
进行调试。 You should by default be able to see the response to these console logs in Cloudwatch:)默认情况下,您应该能够在 Cloudwatch 中看到对这些控制台日志的响应:)
Read more here:在这里阅读更多:
https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-logs.html https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-logs.html
I myself ran into this issue very recently.我自己最近遇到了这个问题。 The solution is:
解决方案是:
The entire content of the JSON object will be returned to the Gateway. JSON object 的全部内容将返回到网关。 Check out this documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
查看此文档: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
I also have a pretty detailed Stackoverflow post on how the Gateway should be configured via Cloudformation YAML file: AWS API Gateway with Lambda Authorizer我还有一篇关于如何通过 Cloudformation YAML 文件配置网关的非常详细的 Stackoverflow 帖子: AWS API Gateway with Lambda Authorizer
It is because of node.js asynchronous call.这是因为 node.js 异步调用。 Your function finishes the running before asynchronous call returns.
您的 function 在异步调用返回之前完成运行。 I fixed some lines of codes.
我修复了一些代码行。 I wish this might be helpful for you.
我希望这可能对您有所帮助。
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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.