最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - importing the request library into AWS Lambda on node.js - Stack Overflow

programmeradmin0浏览0评论

I am calling the request library with const request = require("request")

and I added the dependency in the package.json I have posted the error below. From reading other posts however, I realize i might need to npm-install the request module and import the entire zip as a folder.

Since I am new to node, I wanted to check if there is another way to import the 'require' library into the current working directory or am I making a mistake somewhere else ?

Here is my package.json:

{
  "name": "fact",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ask-sdk-core": "^2.0.0",
    "ask-sdk-model": "^1.0.0",
    "i18next": "^15.0.5",
     "request": "^2.88.0"
  }
}

its still giving me the following error when I test:

Response:
{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'request'",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'request'",
    "    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._pile (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)"
  ]
}

Request ID:
"01b4df3d-e269-4d8a-90a3-7f02b9be9b58"

Function Logs:
START RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58 Version: $LATEST
2020-04-03T18:02:05.453Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'request'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'request'","    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._pile (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)"]}
END RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58
REPORT RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58  Duration: 2159.04 ms    Billed Duration: 2200 ms    Memory Size: 128 MB Max Memory Used: 19 MB  
Unknown application error occurred
Runtime.ImportModuleError

Here is the location where I am using the request: For context its an event handler for an Alexa request.

const checkprof_Handler =  {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest' && request.intent.name === 'checkprof' ;
    },
    handle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        const responseBuilder = handlerInput.responseBuilder;
        let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

        let say = 'Let me check. ';

        let slotStatus = '';
        let resolvedSlot;

        let slotValues = getSlotValues(request.intent.slots); 


        // getSlotValues returns .heardAs, .resolved, and .isValidated for each slot, according to request slot status codes ER_SUCCESS_MATCH, ER_SUCCESS_NO_MATCH, or traditional simple request slot without resolutions

        // console.log('***** slotValues: ' +  JSON.stringify(slotValues, null, 2));
        //   SLOT: name 
        if (slotValues.name.heardAs) {
            slotStatus += ' slot name was heard as ' + slotValues.name.heardAs + '. ';

            var name = slotValues.name.heardAs;
            const url = `.php/
            ${name}`;

            request.get(url, (error, response, body) => {
            let json = JSON.parse(body);
            console.log('error:', error); // Print the error if one occurred
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            console.log('body:', body); // Print the body

            // const theFact = body;                  
            // const speechOutput = theFact;
            // this.response.cardRenderer(SKILL_NAME, theFact);
            // this.response.speak(speechOutput + " Would you like another fact?").listen("Would you like another fact?");
            // this.emit(':responseReady');
        });

            slotStatus +=  slotValues.name.heardAs ;
        } else {
            slotStatus += 'slot name is empty. ';
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_MATCH') {
            slotStatus += 'a valid ';
            if(slotValues.name.resolved !== slotValues.name.heardAs) {
                slotStatus += 'synonym for ' + slotValues.name.resolved + '. '; 
                } else {
                slotStatus += 'match. '
            } // else {
                //
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') {
            slotStatus += 'which did not match any slot value. ';
            console.log('***** consider adding "' + slotValues.name.heardAs + '" to the custom slot type used by slot name! '); 
        }

        if( (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') ||  (!slotValues.name.heardAs) ) {
            slotStatus += 'A few valid values are, ' + sayArray(getExampleSlotValues('checkprof','name'), 'or');
        }

        say += slotStatus;


        return responseBuilder
            .speak(say)
            .reprompt('try again, ' + say)
            .getResponse();
    },
};

I am calling the request library with const request = require("request")

and I added the dependency in the package.json I have posted the error below. From reading other posts however, I realize i might need to npm-install the request module and import the entire zip as a folder.

Since I am new to node, I wanted to check if there is another way to import the 'require' library into the current working directory or am I making a mistake somewhere else ?

Here is my package.json:

{
  "name": "fact",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ask-sdk-core": "^2.0.0",
    "ask-sdk-model": "^1.0.0",
    "i18next": "^15.0.5",
     "request": "^2.88.0"
  }
}

its still giving me the following error when I test:

Response:
{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'request'",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'request'",
    "    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._pile (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)"
  ]
}

Request ID:
"01b4df3d-e269-4d8a-90a3-7f02b9be9b58"

Function Logs:
START RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58 Version: $LATEST
2020-04-03T18:02:05.453Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'request'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'request'","    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._pile (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)"]}
END RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58
REPORT RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58  Duration: 2159.04 ms    Billed Duration: 2200 ms    Memory Size: 128 MB Max Memory Used: 19 MB  
Unknown application error occurred
Runtime.ImportModuleError

Here is the location where I am using the request: For context its an event handler for an Alexa request.

const checkprof_Handler =  {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest' && request.intent.name === 'checkprof' ;
    },
    handle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        const responseBuilder = handlerInput.responseBuilder;
        let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

        let say = 'Let me check. ';

        let slotStatus = '';
        let resolvedSlot;

        let slotValues = getSlotValues(request.intent.slots); 


        // getSlotValues returns .heardAs, .resolved, and .isValidated for each slot, according to request slot status codes ER_SUCCESS_MATCH, ER_SUCCESS_NO_MATCH, or traditional simple request slot without resolutions

        // console.log('***** slotValues: ' +  JSON.stringify(slotValues, null, 2));
        //   SLOT: name 
        if (slotValues.name.heardAs) {
            slotStatus += ' slot name was heard as ' + slotValues.name.heardAs + '. ';

            var name = slotValues.name.heardAs;
            const url = `http://bluetooth-env-test.eba-brqgvwur.us-east-2.elasticbeanstalk./WebApp/search.php/
            ${name}`;

            request.get(url, (error, response, body) => {
            let json = JSON.parse(body);
            console.log('error:', error); // Print the error if one occurred
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            console.log('body:', body); // Print the body

            // const theFact = body;                  
            // const speechOutput = theFact;
            // this.response.cardRenderer(SKILL_NAME, theFact);
            // this.response.speak(speechOutput + " Would you like another fact?").listen("Would you like another fact?");
            // this.emit(':responseReady');
        });

            slotStatus +=  slotValues.name.heardAs ;
        } else {
            slotStatus += 'slot name is empty. ';
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_MATCH') {
            slotStatus += 'a valid ';
            if(slotValues.name.resolved !== slotValues.name.heardAs) {
                slotStatus += 'synonym for ' + slotValues.name.resolved + '. '; 
                } else {
                slotStatus += 'match. '
            } // else {
                //
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') {
            slotStatus += 'which did not match any slot value. ';
            console.log('***** consider adding "' + slotValues.name.heardAs + '" to the custom slot type used by slot name! '); 
        }

        if( (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') ||  (!slotValues.name.heardAs) ) {
            slotStatus += 'A few valid values are, ' + sayArray(getExampleSlotValues('checkprof','name'), 'or');
        }

        say += slotStatus;


        return responseBuilder
            .speak(say)
            .reprompt('try again, ' + say)
            .getResponse();
    },
};
Share Improve this question asked Apr 3, 2020 at 18:08 DhruvDhruv 64510 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

There is no need to create node Module folder in lambda function.Just create a folder and in that install required i.e npm install require and add it to layer in lambda function. For further information refer https://www.freecodecamp/news/lambda-layers-2f80b9211318/

note: use appropriate runtime i.e all available version of nodejs

Yes, you need to install the library with npm. As far I know you have two simple ways to do it, using aws cloud9 or do it in your local environment and upload the lambda to aws.

In order to do that from your local environment, just download your function as a zip, doing click on export function and selecting "Download deployment package":

This will donwload a zip to your local environment, unzip it and inside the folder, open the terminal and install your dependency:

npm i request

zip the folder again and deploy it to aws using the aws-cli:

aws lambda update-function-code --function-name=your_function_name --zip-file fileb://your_zip_file_name.zip
发布评论

评论列表(0)

  1. 暂无评论