简体   繁体   English

AWS API 网关与 Lambda HTTP GET 请求(Node.js)502 错误网关

[英]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&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);
};

I see couple of things.我看到了几件事。

  • We need to get the values from method 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 也要捕获错误,所以我采用了第二种方法。
  • We also need to resolve or reject the actual response from within promise.我们还需要解决或拒绝 promise 内部的实际响应。

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.

相关问题 AWS Lambda 与 API 网关和 Node.js 返回 HTTP 50 - AWS Lambda with API gateway and Node.js returning HTTP 502 节点 JS AWS 无服务器 502 HTTP/1.1 502 错误网关 - Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway 如何使用Javascript(Node.js)读取通过Http Post发送的变量值并在AWS API Gateway Lambda上获取? - How to read variable value sent over Http Post and Get on AWS API Gateway Lambda using Javascript(Node.js)? Node.js/Express.js/consign(): 默认请求有效 ("/") 但 ("/tasks") 返回 502:Bad Gateway - Node.js/Express.js/consign(): default request works ("/") but ("/tasks") returns a 502:Bad Gateway 尽管CORS配置正确,但CORS 502 Bad Gateway,AWS Elastic Beanstalk Node.js服务器 - CORS 502 Bad Gateway, AWS Elastic Beanstalk Node.js server, despite proper CORS configuration Node.js和Docker- Elastic Beanstalk 502错误网关 - Node.js and Docker- Elastic Beanstalk 502 Bad Gateway 带有 nginx 502 错误网关错误的 node.js 应用程序 - node.js app with nginx 502 bad gateway error 在 node.js 的生产服务器上获取 502 Bad Gateway - Getting 502 Bad Gateway on the production server for node.js 弹性beantalk上的node.js:Firefox 502错误网关 - node.js on elastic beanstalk: firefox 502 bad gateway (Cloud Foundry, Node.js) 502 Bad Gateway:注册端点无法处理请求 - (Cloud Foundry, Node.js) 502 Bad Gateway: Registered endpoint failed to handle the request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM