【问题标题】:Invoking an api inside a aws lambda but getting a null response在 aws lambda 中调用 api 但得到空响应
【发布时间】:2020-04-21 22:22:36
【问题描述】:

我正在尝试在 API 中调用休息 API,但它没有返回任何内容。所以我正在制作一个简单的 lambda,它返回一个 JSON,但得到一个空值作为响应。

var https = require('https');
var dt;
exports.handler = async (event, context) => {
      var data = '';

    return new Promise((resolve, reject) => {
      var params = {
                host: "cvwtzygw4a.execute-api.ap-south-1.amazonaws.com",
                path: "/test/first"
                };

        const req = https.request(params, (res) => {
          console.log('STATUS: ' + res.statusCode);
           res.setEncoding('utf8');
           res.o n('data', function(chunk) {
               data += chunk;
             });
         res.on('end', function() {
          console.log("DONE");

          console.log(data);
           dt = JSON.parse(data);
          console.log(dt);
         });


      resolve(dt);
    });

    req.on('error', (e) => {
      reject(e.message);
    });

    // send the request
    req.write('');
    req.end();
 });
};

【问题讨论】:

标签: javascript api aws-lambda aws-api-gateway


【解决方案1】:

您应该通过this article 了解如何在 AWS Lambda 中使用 NodeJs Promise。在此,second solution 解决了您的用例。

为了具体到您的代码,我使用 async/await 语法和 request-promise 库对其进行了修改以使其非常简单。

const request = require('request-promise');
exports.handler = async (event, context) => {
    var data = '';

    try {
        data = await request.get('https://cvwtzygw4a.execute-api.ap-south-1.amazonaws.com/test/first');
        console.log('response received', res);
    } catch (error) {
        console.log('Error', error);
    }
    return data;
};

以下是输出:

START RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7 Version: $LATEST
2020-01-03T17:51:19.987Z        80d75f93-5fa6-1354-c22c-0597beb075e7    response received {
"basic" : {"name":"John","age":31,"city":"New York"}
}
END RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7
REPORT RequestId: 80d75f93-5fa6-1354-c22c-0597beb075e7  Init Duration: 907.81 ms        Duration: 1258.54 ms    Billed Duration: 1300 ms        Memory Size: 128 MB       Max Memory Used: 55 MB

"{\n\"basic\" : {\"name\":\"John\",\"age\":31,\"city\":\"New York\"}\n}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2019-06-27
    • 2015-12-04
    • 2021-09-09
    • 2020-02-27
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多