AWS Lambda http 请求:无法将正文字符串化为 json:将循环结构转换为 JSON

AWS Lambda http request: Unable to stringify body as json: Converting circular structure to JSON

我想return我的 AWS Lambda 函数中的 HTTP 请求的结果:

var http = require('http');

exports.someFunction = function(event, context) {
     var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
     http.get(url, function(res) {
            context.succeed(res);
          }).on('error', function(e) {
            context.fail("Got error: " + e.message);
          });
}

它应该 return 正是我在浏览器中直接打开 url 时得到的结果(尝试查看预期的 json)。

AWS Lambda return 当我调用 context.succeed(res) 时出现以下错误消息:

{
  "errorMessage": "Unable to stringify body as json: Converting circular structure to JSON",
  "errorType": "TypeError"
}

我假设我需要使用 res 的一些 属性 而不是 res 本身,但我不知道哪一个包含我想要的实际数据。

如果您使用原始 http 模块,您需要监听 dataend 事件。

exports.someFunction = function(event, context) {
    var url = "http://router.project-osrm.org/trip?loc=47.95,12.95&loc=47.94,12.94";
    http.get(url, function(res) {
        // Continuously update stream with data
        var body = '';
        res.on('data', function(d) {
            body += d;
        });
        res.on('end', function() {
            context.succeed(body);
        });
        res.on('error', function(e) {
            context.fail("Got error: " + e.message);
        });
    });
}

使用另一个模块,例如 request https://www.npmjs.com/package/request 可以做到这一点,这样您就不必管理这些事件,并且您的代码几乎可以恢复到以前的状态。