Chris
Chris

Reputation: 14218

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

I would like to return the result of an HTTP request in my AWS Lambda function:

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

It should return exactly what I get when I open the url directly in my browser (try it to see the expected json).

AWS Lambda return the following error message when I call context.succeed(res):

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

I assume that I need to use some property of res instead of res itself, but I couldn't figure out which one contains the actual data I want.

Upvotes: 2

Views: 6907

Answers (1)

Ryan
Ryan

Reputation: 5973

If you are using the raw http module you need to listen for data and end events.

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

Using another module such as request https://www.npmjs.com/package/request would make it so you don't have to manage those events and your code could go back to almost what you had before.

Upvotes: 2

Related Questions