[英]AWS API Gateway with Lambda HTTP GET Request (Node.js) 502 Bad Gateway
I'm new to AWS lambda functions and NodeJS.我是 AWS lambda 函数和 NodeJS 的新手。 I'm trying to create an API Gateway call to a Lambda function that calls an external API and return some JSON data.
I'm trying to create an API Gateway call to a Lambda function that calls an external API and return some JSON data. It took me a while but I was finally able to get something to work based on this post: AWS Lambda HTTP POST Request (Node.js)
我花了一段时间,但我终于能够根据这篇文章得到一些工作: AWS Lambda HTTP POST Request (Node.js)
The problem was the API Gateway kept erroring with a 502 Bad Gateway;问题是 API 网关不断出错,出现 502 错误网关; which turns out to be that the JSON response was malformed.
结果证明 JSON 响应格式不正确。 In the post I referenced above everyone seem to have success with just returning the JSON as-is, but I had to follow the instructions here to fix my issue: https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/
在我上面提到的帖子中,每个人似乎都成功地按原样返回 JSON,但我必须按照此处的说明来解决我的问题: https://aws.amazon.com/premiumsupport/knowledge-center/malformed -502-api-网关/
My question is: if you look at the last 10 lines of my code that finally worked I had to reformat my response, as well as use a callback in a async function.我的问题是:如果您查看我最后工作的代码的最后 10 行,我必须重新格式化我的响应,并在异步 function 中使用回调。 I am new to nodeJS and Lambda but it looks wrong to me, even though it works.
我是 nodeJS 和 Lambda 的新手,但它看起来不对,即使它有效。 The post I referenced seem to have much more elegant code, and I hope someone can tell me what I am doing wrong.
我引用的帖子似乎有更优雅的代码,我希望有人能告诉我我做错了什么。
const https = require('https');
var responseBody = {"Message": "If you see this then the API call did not work"};
const doGetRequest = () => {
return new Promise((resolve, reject) => {
const options = {
host: 'my.host.com',
path: '/api/v1/path?and=some¶meters=here',
method: 'GET',
headers: {
'Authorization': 'Bearer token for testing',
'X-Request-Id': '12345',
'Content-Type': 'application/json'
}
};
var body='';
//create the request object with the callback with the result
const req = https.request(options, (res) => {
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Result", body.toString());
responseBody = body;
});
resolve(JSON.stringify(res.statusCode));
});
// handle the possible errors
req.on('error', (e) => {
reject(e.message);
});
//finish the request
req.end();
});
};
exports.handler = async (event, context, callback) => {
await doGetRequest();
var response = {
"statusCode": 200,
"headers": {
"my_header": "my_value"
},
"body": JSON.stringify(responseBody),
"isBase64Encoded": false
};
callback(null, response);
};
I see couple of things.我看到了几件事。
doGetRequest
and use the response, we can do that by await response = doGetRequest()
or doGetRequest.then()
, since we ant to capture errors as well, i went with second method.doGetRequest
获取值并使用响应,我们可以通过await response = doGetRequest()
或doGetRequest.then()
来做到这一点,因为我们 ant 也要捕获错误,所以我采用了第二种方法。 I tested with a different api(with url of this question).我用不同的api进行了测试(这个问题的url)。 Here is the updated code.
这是更新的代码。
const https = require('https');
var responseBody = {"Message": "If you see this then the API call did not work"};
const doGetRequest = () => {
return new Promise((resolve, reject) => {
const options = {
host: 'stackoverflow.com',
path: '/questions/66376601/aws-api-gateway-with-lambda-http-get-request-node-js-502-bad-gateway',
method: 'GET'
};
var body='';
//create the request object with the callback with the result
const req = https.request(options, (res) => {
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Result", body.toString());
resolve(body);
});
});
// handle the possible errors
req.on('error', (e) => {
reject(e.message);
});
//finish the request
req.end();
});
};
exports.handler = (event, context, callback) => {
console.log('event',event, 'context',context);
doGetRequest().then(result => {
var response = {
"statusCode": 200,
"headers": {
"my_header": "my_value"
},
"body": JSON.stringify(result),
"isBase64Encoded": false
};
callback(null, response);
}).catch(error=> {
callback(error);
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.