json - AWS Lambda http请求: Unable to stringify body as json: Converting circular structure to JSON

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

我想在我的 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 本身,但我无法弄清楚哪个属性包含我想要的实际数据。

最佳答案

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

关于json - AWS Lambda http请求: Unable to stringify body as json: Converting circular structure to JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35276297/

相关文章:

javascript - 我无法将 JSON 数据放入数组中

java - 如何将驻留在 Amazon ec2 实例中的 Tomcat 7 server.xml 文档库指向 Amazon S3 存储桶中的文件夹

amazon-web-services - AWS - 同一域的跨区域 SSL 证书

spring-boot - Zuul代理向请求url添加参数

asp.net - 如何获得请求的数字签名(在双向 SSL 中)?

c# - 如何使多个 API 调用更快?

javascript - 是否有在 HTML 中嵌入 JSON 的标准?

ios - 解析 JSON 数据并处理数组

json - 如何在 NodeJS 中成功解析 FFMpeg 的输出

amazon-web-services - 如何支付 AWS