Search code examples
node.jsamazon-web-servicesaws-lambdaserverless

Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless


I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console. One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues. project directory image

This is the sample code which is throwing error

    const { IamAuthenticator } = require('ibm-watson/auth');
    const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

    async function textAnalyse(req, res) {
      const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
      version: '2019-07-12',
      authenticator: new IamAuthenticator({
        apikey: 'API KEY'
      }),
    url: 'https://URL/natural-language-understanding/api'
    });

    const analyzeParams = {
       'text': HtmlToText.fromString('Test text here'),
       'features': {
         'entities': {
           'sentiment': true,
           'limit': 100
          }
        }
    };

    const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);

    // prepare the response object
    res.send({ analysis: analysis });
  }

Error in AWS Cloud watch { "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module 'axios/lib/utils'", "stack": [ "Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'", " at _loadUserApp (/var/runtime/UserFunction.js:100:13)", " at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)", " at Object.<anonymous> (/var/runtime/index.js:45:30)", " at Module._compile (internal/modules/cjs/loader.js:778:30)", " at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)", " at Module.load (internal/modules/cjs/loader.js:653:32)", " at tryModuleLoad (internal/modules/cjs/loader.js:593:12)", " at Function.Module._load (internal/modules/cjs/loader.js:585:3)", " at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)", " at startup (internal/bootstrap/node.js:283:19)", " at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)" ] }


Solution

  • I found the fixes for this. when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency

    "dependencies": {
        "axios": "^0.19.2"
      }
    

    Then add the layer in the functions from AWS UI, left side menu Steps to Add layer

    Then add the layer to your function Added layer to the function

    Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.