Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-fetch not working with AWS lambda function ("cannot find node-fetch")

Basically I am trying to invoke a lambda function from an API Gateway. The API is called from an index.html file I made that calls the api with a button click and returns values (ideally the weather). I can get it to return some text values but whenever I try to actually call an API with the lambda function using node-fetch function it gives me an error saying "cannot find node-fetch module."

const fetch = require('node-fetch')

module.exports.getTulsaCurrentWeather = (event, context, callback) => {

//API endpoint
const endpoint = `http://api.openweathermap.org/data/2.5/weather? 
APPID=${process.env.APPID}&q=Tulsa&units=imperial`;

fetch(endpoint)
.then( res => res.json() )
.then( body =>  {
const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*",
  },
  body: JSON.stringify({ temperature: body.main.temp })
};

callback(null, response);
});
};
like image 750
Chase Avatar asked Dec 10 '20 01:12

Chase


People also ask

Is node-fetch included in node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node.

Is node-fetch the same as fetch?

fetch() function. In NodeJS, several packages/libraries can achieve the same result. One of them is the node-fetch package. node-fetch is a lightweight module that enables us to use the fetch() function in NodeJS, with very similar functionality as window.

Does AWS lambda support node JS?

You can now develop AWS Lambda functions using the Node. js 16 runtime. This version is in active LTS status and considered ready for general use. To use this new version, specify a runtime parameter value of nodejs16.


1 Answers

See How do I build a Lambda deployment package for Node.js?

A common error with Lambda functions in Node.js is "cannot find module." This error is usually caused when your deployment package doesn't have the correct folder structure for the Lambda service to load your modules and libraries, or it has incorrect file permissions. (Lambda requires global read permissions.)

Follow these instructions to build a deployment package that includes the function code in the root of the .zip file with read and execute permissions for all files.

Note that your code wouldn't run outside of Lambda either, for example on your own machine, unless you had previously installed the node-fetch package from NPM.

The analogous process in AWS Lambda is to package and upload your third-party dependencies, or deploy the packages to a Lambda Layer and configure your Lambda function to use that layer. Lambda will not npm install node-fetch for you.

like image 116
jarmod Avatar answered Nov 15 '22 04:11

jarmod