【问题标题】:AWS Lambda http request: Unable to stringify body as json: Converting circular structure to JSONAWS Lambda http 请求:无法将正文字符串化为 json:将循环结构转换为 JSON
【发布时间】:2016-02-08 18:06:09
【问题描述】:

我想在我的 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);
          });
}

当我直接在浏览器中打开 url 时,它应该返回我得到的内容(尝试查看预期的 json)。

当我调用context.succeed(res) 时,AWS Lambda 返回以下错误消息:

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

我假设我需要使用res 的某些属性而不是res 本身,但我无法弄清楚哪个包含我想要的实际数据。

【问题讨论】:

    标签: json amazon-web-services httprequest aws-lambda


    【解决方案1】:

    如果您使用的是原始 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,这样您就不必管理这些事件,您的代码几乎可以恢复到以前的状态。

    【讨论】:

    • 嗨瑞恩。您能告诉我如何使用您在此处提到的 AWS Lambda 的 Request 吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 2016-01-11
    • 2016-12-18
    • 2017-04-03
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多