How to use request module in node.js lambda

I am trying to use the request module in AWS Lambda for Node.js, but I am not having good results.

This is the function I have so far:

const request = require('request');
url = 'https://www.google.com'

exports.handler = async (event) => {

    request(url, (error,res,body) => {
        console.log(error);    //this is not printing
        console.log(res);      //this is not printing
        console.log(body);     //this is not printing
        console.log('Come on!!'); //this is not printing
    });

    console.log(url); //This is the only thing printing, you can see in the Function Logs below, second line.

};

and this is the response I am getting:

Response:
null

Request ID:
"3e46f401-f26d-435d-90be-ac848c6c3a39"

Function Logs:
START RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39 Version: $LATEST
2019-10-14T08:06:23.755Z    3e46f401-f26d-435d-90be-ac848c6c3a39    INFO    https://www.google.com
END RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39
REPORT RequestId: 3e46f401-f26d-435d-90be-ac848c6c3a39  Duration: 368.93 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 92 MB  Init Duration: 461.54 ms

I am wondering why I am not getting any response from inside the requests method. I tried on my laptop and the part of the code outside the handler works just fine.

I uploaded the project as a zip file, so the node_modules folder with the request module is indeed there. I noted a couple of solutions using the http module instead of request, but I would like to understand first why this is not working, before moving to a different solution.

Upvotes: 1

Views: 2767

Answers (1)

mtkopone
mtkopone

Reputation: 6443

Your function is marked as async, yet you are using a callback to handle the response. So nothing is being awaited on.

This means that your function returns an implicit promise that is already fulfilled. This makes the lambda stop. So, either:

A) Write your code using async/await, which probably requires request-promise or similar:

exports.handler = async event => {
    const res = await promisifiedRequest(url);
    console.log(res.statusCode);
    console.log(url);
};

or

B) Convert the function from async/await to use callbacks, like so:

exports.handler = (event, context, callback) => {
    const res = request(url, (error, res, body) => {
        console.log('Come on!!');
        callback(null, res.statusCode);
    });
    console.log(url);
};

Upvotes: 2

Related Questions