[英]Rest-API call fails in lambda function
我對 AWS 中的 lambda 函數很陌生,我需要一些建議來找出問題的本質。 AWS Lambda function 基於 Javascript 使用 node.js 12.x。 我確實在 Ubuntu 18.04 和 MacOs Catalina 上設置了基於 SAM (sam cli/aws cli/docker/IntelliJ) 的本地開發環境和一個簡單的基本 lambda function 工作,在兩個系統上。 當 docker 運行時,我可以設置日志並通過 IntelliJ 查看它們。 function 是使用來自終端的 sam init 命令並選擇一個簡單的 hello world 創建的。
我確實在其中添加了一個 Rest-API 調用。 沒什么特別的,使用請求 2.88.2(我知道它已被棄用,我確實嘗試使用其他方法,但無論如何都失敗了,所以我現在堅持請求)。
基本上發生的事情是對 API 的調用“似乎”根本沒有發生。 顯示 API 呼叫前后的日志。 API 調用中的日志,例如顯示錯誤或結果,從未顯示。 到目前為止,只有在一種情況下,當我刪除 URI 時,我才能看到來自 API 的錯誤消息。 正如預期的那樣,API 返回了一條錯誤消息:無效的 URI。
否則什么都沒有。 這里有一些代碼。 這個 function 是從 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 並且正在工作。 請求中的所有日志都不會出現。 無論更改選項(確實嘗試了許多不同的方法)。 我究竟做錯了什么? 關於如何跟蹤此問題的任何建議?
謝謝
史蒂夫
這是正確的行為。 因為 function getToken
沒有等待 http 請求完成。 您應該將 function 轉換為使用 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, function (err, response, 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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.