2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Ryan. Would you be able to tell me how I use Request that you mentioned here with AWS Lambda?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.