问题描述
我对AWS中的lambda函数是陌生的,我需要一些建议来弄清楚问题的性质。 使用node.js 12.x的基于Javascript的AWS Lambda函数。 我确实在两个系统上都基于Ubuntu 18.04和MacOs Catalina上的SAM(sam cli / aws cli / docker / IntelliJ)设置了本地开发环境,并完成了一个简单的基本lambda函数。 我可以设置日志,并在docker运行时通过IntelliJ看到它们。 该功能是使用终端的sam init命令并选择一个简单的hello世界创建的。
我确实在其中添加了Rest-API调用。 没什么好想的,使用请求2.88.2(我已经过时了,我确实尝试过使用其他方法,但是它们都以失败告终,所以我现在仍然坚持请求)。
基本上,正在发生的事情是对API“似乎”的调用根本没有发生。 显示在API调用之前和之后的日志。 API调用内的日志(例如显示错误或结果)永远不会显示。 到目前为止,只有在一种情况下,当我删除URI时,才能看到来自API的错误消息。 正如预期的那样,API返回了一条错误消息:无效的URI。
否则,什么都没有。这里有一些代码。 从lambda处理程序中调用此函数。
function getToken() {
const request = require('request');
const qs = require('querystring');
console.log("getToken function called");
let bodyData = qs.stringify({
username: 'test',password: 'xxxxx',grant_type: 'password'
});
console.log("getToken bodyData : " + bodyData);
let options = {
url: "https://blahblahblah/function",method: 'POST',headers: {
'Content-Type': 'application/x-www-form-urlencoded','Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},form: bodyData
};
console.log("getToken options : " + options);
var request1 = request(options,function(err,response,body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
return null;
} else {
console.log("Answer from getToken : " + body);
return body;
}
});
}
我确实使用Postman测试了连接和API,并且正在工作。 请求中的所有日志永远不会出现。 无论更改选项(尝试了多种方法)。 我究竟做错了什么 ? 关于如何跟踪此问题有什么建议吗?
谢谢
史蒂夫
解决方法
这是正确的行为。因为函数getToken
没有等待http请求完成。您应该将函数转换为使用promise / async-await或简单地回调。
承诺
async function getToken() {
...
return new Promise((resolve,reject) => {
request(options,function (err,response,body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
resolve(null);
} else {
console.log("Answer from getToken : " + body);
resolve(body);
}
});
});
}
// Then in the lambda Handler:
// await getToken()
回调
function getToken(callback) {
...
request(options,body) {
console.log("returned from API call");
if (err) {
console.log("Error from getToken : " + err);
callback(null);
} else {
console.log("Answer from getToken : " + body);
callback(body);
}
});
}
// Then in the lambda
getToken(() => {
// handle the http request response
})