在 AWS Lambda 中调用 API,但收到了空响应。

huangapple go评论77阅读模式
英文:

Invoking an api inside a aws lambda but getting a null response

问题

我正在尝试在一个API内部调用一个REST 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.on('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();
    });
};

如果您需要进一步的帮助或解释,请告诉我。

英文:

I am trying to invoke a rest API inside an API but it is not returning anything. So I am making a simple lambda which returns a JSON but getting a null value as a response.

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

答案1

得分: 1

你应该阅读这篇文章以了解如何在AWS Lambda中使用NodeJs promises。在其中,第二种解决方案适用于你的用例。

具体到你的代码,我进行了修改,使用了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', data);
    } 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

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

You should go through this article to understand how to use NodeJs promises in AWS Lambda. In this, the second solution addresses your use case.

To be specific to your code, I modified to make it very simple using the async/await syntax and the request-promise library.

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

Following was the output:

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}"

huangapple
  • 本文由 发表于 2020年1月3日 18:42:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定