How to make HTTPS request in Lambda (not using API gateway)

0

My intention is to make a simple HTTP request and grab the JSON response body. Here are my code but it seems like the log complained bout missing packages. Test Event Name

call

Response
{
  "errorType": "Error",
  "errorMessage": "Cannot find package 'axios' imported from /var/task/index.mjs",
  "trace": [
    "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'axios' imported from /var/task/index.mjs",
    "    at new NodeError (node:internal/errors:405:5)",
    "    at packageResolve (node:internal/modules/esm/resolve:892:9)",
    "    at moduleResolve (node:internal/modules/esm/resolve:985:20)",
    "    at moduleResolveWithNodePath (node:internal/modules/esm/resolve:936:12)",
    "    at defaultResolve (node:internal/modules/esm/resolve:1178:79)",
    "    at nextResolve (node:internal/modules/esm/loader:163:28)",
    "    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)",
    "    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)",
    "    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)",
    "    at link (node:internal/modules/esm/module_job:76:36)"
  ]
}

I saw some article claiming to zip and upload the project folder, is there a way to jz code in console using standard library/package?

import axios from 'axios';

async function makeHttpRequest(url) {
  try {
    const response = await axios.get(url);
    console.log('Response data:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error making HTTP request:', error.message);
    throw error;
  }
}

export const handler = async (event) => {
  const url = 'https://jsonplaceholder.typicode.com/posts/1'; // Example URL
makeHttpRequest(url);

  // TODO implement
  const response = {
    statusCode: 200,
    // body: JSON.stringify('Hello from Lambda!') + ,
    body: makeHttpRequest(url)
  };
  return response;
};
weilies
asked 7 months ago2345 views
4 Answers
0
Accepted Answer

Hit error with sample code above :)

Really? It works perfectly for me.

Enter image description here

Judging from index.mjs file you use, do you use ES Modules? My version is index.js that uses CommonJS module.

I'll give you my full Lambda configuration. There may be some differences between yours.

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: My serverless stack

Resources:
  HttpRequestFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName:
        Fn::Sub: ${AWS::StackName}-HttpRequestFunction
      Description: Send an HTTP request
      Handler: index.handler
      Runtime: nodejs18.x
      Architectures:
        - arm64
      InlineCode: |
        const http = require("node:http");

        exports.handler = async () => {
          const globalIpAddress = await new Promise((resolve, reject) => {
            const req = http.request(
              { hostname: "ifconfig.me", port: 80, path: "/", method: "GET" },
              res => {
                res.on("data", chunk => {
                  const body = chunk.toString();
                  resolve(body);
                });
              },
            );
            req.on("error", e => {
              reject(e.message);
            });
            req.end();
          });

          return globalIpAddress;
        };
profile picture
HS
answered 7 months ago
  • cool! it's working now!

0

If you want to send HTTP request with Node.js standard library, http.request should be your friend. Here's a sample implementation:

const http = require("node:http");

exports.handler = async () => {
  const globalIpAddress = await new Promise((resolve, reject) => {
    const req = http.request(
      { hostname: "ifconfig.me", port: 80, path: "/", method: "GET" },
      res => {
        res.on("data", chunk => {
          const body = chunk.toString();
          resolve(body);
        });
      },
    );
    req.on("error", e => {
      reject(e.message);
    });
    req.end();
  });

  return globalIpAddress;
};

If you want to use HTTPS instead, then replace http to https and port 80 to 443.

profile picture
HS
answered 7 months ago
0

Hello,

From the error it looks like your function is not able to fetch the required dependencies to run the function successfully. This may be because your layer content is not packaged properly. A Lambda layer is a .zip file archive that contains supplementary code or data. Layers usually contain library dependencies (such as axios), a custom runtime, or configuration files.

Please take a look at the following links to get more insights into layers and how to package them. https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html https://docs.aws.amazon.com/lambda/latest/dg/packaging-layers.html

Make sure your zip contains correct directory structure as mentioned in the above links. Hope this helps.

AWS
answered 7 months ago
0

Hit error with sample code above :)

Hit error with sample code above :)

weilies
answered 7 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions