2

Trying to execute a AWS Lambda in NodeJS (newbie to nodeJs) in which I make a http request. At the end of Lambda execution, I wish to return response code and response message of http request.

Making the http request call:

var executeRequest = function(request, callback) {

const req = https.request(request, (res) => {

  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
     process.stdout.write(d);
  });
  callback(res);
});

req.on('error', (e) => {
  console.error(e);
});

req.end(request.body);

};

Lambda Code:

    exports.handler = (event, context, callback) => {

    // Formulate request 

    var result = executeRequest(request, function(response) {
         console.log("Response Code: ", response.statusCode);
         console.log("Response Message: ", response.statusMessage);
         // Successfully able to print the response above

        return response;
     });
     console.log("Result Response Code: ", result);
     console.log("Result Response Message: ", result);
     } 

I wish to return the response.statusCode and response.statusMessage as response from Lambda

return{
    statusCode: <the code>,
    body: <the message>,
};

However, the result is populated as undefined. How to extract the required response parameter so they can be returned correctly?

** Edit: ** Snippet after changes suggested: Code using Promise:

var executeRequest = function(request, callback) {

    return new Promise((resolve, reject) => {
        https.request(request, function(res) {
            if(res.statusCode==200 || res.statusCode==404) {
                resolve(res);
            }
            else {
                console.error(res);
                reject(res.statusCode);
            }
        }).end(request.body || '');
    });
};


exports.handler = (event, context, callback) => {

    // Formulate request 

    var value = executeRequest(request).then(function(result) {
  console.log("Result ", result);
  const response = { statusCode: 200, body: JSON.stringify('Hello from Lambda!') }; 
  return response;
 });

    console.log(value);
}
4
  • Can you post what is the current result you get ? Commented May 23, 2019 at 20:54
  • @ Kannaiyan : Result Response Code: undefined Result Response Message: undefined Commented May 23, 2019 at 20:55
  • might be easier with npm package request. Commented May 23, 2019 at 20:58
  • Move your console.log lines inside the "result" function, otherwise they will always be undefined (place them before return response) Commented May 23, 2019 at 21:01

3 Answers 3

3

Problem is that your executeRequest is asynchronous and your lambda doesn't know about that so it will simply return right away.

Instead of returning the response, pass it to callback as the second argument (first is error object)

callback(null, response)

This part is executed and without waiting for the executeRequest response, the rest of the code is executed

var result = executeRequest(request, function(response) {
     console.log("Response Code: ", response.statusCode);
     console.log("Response Message: ", response.statusMessage);
     // Successfully able to print the response above

    return response;
 });

So at this point

console.log("Result Response Code: ", result);
console.log("Result Response Message: ", result);

The result is still empty.

So you should instead do something like this.

var result = executeRequest(request, function(response) {
     console.log("Response Code: ", response.statusCode);
     console.log("Response Message: ", response.statusMessage);
     // Successfully able to print the response above

     callback(null, response);
 });
Sign up to request clarification or add additional context in comments.

6 Comments

Getting response: ReferenceError: callback is not defined
You need to place the above code into the exports.handler body where the callback is defined, I will update the code snippet
Probably miinterpretating your comment. :( ... I have edited my question to include code based on suggested answer along with log statement being printed.
Asynchronous is the issue. Try using promises.
@Hans-Eric Lippke: Do you have code snippet I can reference? I have edited the question section to include using Promises. I however get INFO Promise { <pending> } in the logs
|
1

Try something like this.

exports.handler = function( event, context, callback ) { 
 //this is to allow function to return as soon as result is shown
 context.callbackWaitsForEmptyEventLoop = false;
 var request = ...//I expect request is a predefined value or define the request here.

 executeRequest(request).then( function( result ) { 


  //keep all console log before return.
  console.log("Result ", result);

  const response = { statusCode: 200, body: JSON.stringify('Hello from Lambda!') }; 

  callback(null, response);
  return;
 });
}
function executeRequest(request){
   return new Promise( ( resolve, reject ) => {

    https.request(request, function(res) {

     if(res.statusCode==200 || res.statusCode==404) {
        resolve(res);
     }else {
        console.error(res);
        reject(res.statusCode);
        return;
     }
    }).end(request.body || '');
  });
}

Comments

0

Change your Lambda code to the following,

exports.handler = (event, context, callback) => {

    // Formulate request 

    var result = executeRequest(request, function(response) {
         console.log("Response Code: ", response.statusCode);
         console.log("Response Message: ", response.statusMessage);
         // Successfully able to print the response above

        callback(null, response);
     });

     } 

Hope it helps.

4 Comments

Getting error: ReferenceError: callback is not defined
You might have typed it, instead of copy paste. You can see it is defined with the arrow function.
@Kanniyan: Probably miinterpretating your comment. :( ... I have edited my question to include code based on suggested answer along with log statement being printed.
console.log("Test response1: ", result); console.log("Test response2: ", callback); Since the function is not a synchronous call. You cannot print the variable outside of the function. You can try to use async and await.

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.