首页 > 解决方案 > 带有 Lambda HTTP GET 请求 (Node.js) 502 错误网关的 AWS API 网关

问题描述

我是 AWS lambda 函数和 NodeJS 的新手。我正在尝试创建对 Lambda 函数的 API Gateway 调用,该函数调用外部 API 并返回一些 JSON 数据。我花了一段时间,但我终于能够根据这篇文章得到一些工作: AWS Lambda HTTP POST Request (Node.js)

问题是 API 网关不断出错,出现 502 Bad Gateway;原来是 JSON 响应格式错误。在我上面引用的帖子中,每个人似乎都成功地按原样返回 JSON,但我必须按照此处的说明来解决我的问题: https ://aws.amazon.com/premiumsupport/knowledge-center/malformed -502-api-网关/

我的问题是:如果您查看我最后工作的代码的最后 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);
};

标签: node.jsamazon-web-servicesaws-lambdaaws-api-gateway

解决方案


我看到了几件事。

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

我用不同的 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);
    })
};

推荐阅读