AWS API Gateway with Lambda HTTP GET Request (Node.js) 502 B



我是AWS lambda函数和NodeJS的新手。我试图创建一个API网关调用Lambda函数,调用外部API并返回一些JSON数据。这花了我一段时间,但我终于能够得到一些工作基于这篇文章:AWS Lambda HTTP POST请求(Node.js)

问题是API网关一直出错502坏网关;结果是JSON响应格式错误。在我上面提到的帖子中,每个人似乎都成功地返回了JSON原样,但我不得不按照这里的说明来解决我的问题:https://aws.amazon.com/premiumsupport/knowledge center/malformed - 502 - api - gateway/

问题是:如果你看一下我的最后10行代码,我不得不重新格式化我的响应,并在异步函数中使用回调。我是新的nodeJS和Lambda,但它看起来不对我,即使它的工作。我引用的帖子似乎有更优雅的代码,我希望有人能告诉我我做错了什么。

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&parameters=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);
};

我看到了一些东西。

  • 我们需要从方法doGetRequest获取值并使用响应,我们可以通过await response = doGetRequest()doGetRequest.then()来做到这一点,因为我们也想捕获错误,所以我使用了第二种方法。
  • 我们还需要在承诺内解决或拒绝实际响应。

我测试了一个不同的api(这个问题的url)。以下是更新后的代码:

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

最新更新